2017-02-19 01:03:48 +08:00
|
|
|
#include <atomic>
|
|
|
|
#include <chrono>
|
|
|
|
#include <mutex>
|
|
|
|
#include <thread>
|
|
|
|
#include <vector>
|
|
|
|
|
2017-10-11 19:19:10 +08:00
|
|
|
#include "glog/logging.h"
|
|
|
|
|
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);
|
|
|
|
|
2017-10-11 19:19:10 +08:00
|
|
|
CHECK(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));
|
|
|
|
|
|
|
|
for (auto& thread : threads) {
|
|
|
|
thread.join();
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|