2017-02-19 01:03:48 +08:00
|
|
|
#include <atomic>
|
|
|
|
#include <chrono>
|
|
|
|
#include <mutex>
|
|
|
|
#include <thread>
|
|
|
|
#include <vector>
|
|
|
|
|
2019-12-09 00:04:06 +08:00
|
|
|
#include "utils/spin_lock.hpp"
|
2017-02-19 01:03:48 +08:00
|
|
|
|
|
|
|
int x = 0;
|
2018-05-30 19:00:25 +08:00
|
|
|
utils::SpinLock lock;
|
2017-02-19 01:03:48 +08:00
|
|
|
|
|
|
|
void test_lock() {
|
|
|
|
using namespace std::literals;
|
|
|
|
|
|
|
|
{
|
2018-05-30 19:00:25 +08:00
|
|
|
std::unique_lock<utils::SpinLock> guard(lock);
|
2017-02-19 01:03:48 +08:00
|
|
|
x++;
|
|
|
|
|
|
|
|
std::this_thread::sleep_for(25ms);
|
|
|
|
|
2021-01-21 22:47:56 +08:00
|
|
|
MG_ASSERT(x < 2,
|
|
|
|
"x always has to be less than 2 (other "
|
|
|
|
"threads shouldn't be able to change the x simultaneously");
|
2017-02-19 01:03:48 +08:00
|
|
|
x--;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
constexpr int N = 16;
|
|
|
|
std::vector<std::thread> threads;
|
|
|
|
|
|
|
|
for (int i = 0; i < N; ++i) threads.push_back(std::thread(test_lock));
|
|
|
|
|
2021-01-21 22:47:56 +08:00
|
|
|
for (auto &thread : threads) {
|
2017-02-19 01:03:48 +08:00
|
|
|
thread.join();
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|