#include <string>
#include <iostream>
#include <thread>
#include <atomic>
class spin_lock{
private:
std::atomic<bool> flag = ATOMIC_VAR_INIT(false);
public:
spin_lock() = default;
spin_lock(const spin_lock&) = delete;
spin_lock& operator = (const spin_lock&) = delete;
void lock() {
bool expected = false;
while (!flag.compare_exchange_strong(expected, true)) {
expected = false;
}
}
void unlock() {
flag.store(false);
}
};
int g_test = 0;
spin_lock g_spinlck;
void work(int& thread_no) {
for (int i = 0;i < 1000;i++) {
g_spinlck.lock();
g_test++;
std::cout << "thread_no : " << thread_no << " ; g_test : " << g_test << std::endl;
g_spinlck.unlock();
}
}
int main()
{
int thread_no0 = 0;
int thread_no1 = 1;
std::thread thd1(work, std::ref(thread_no0));
std::thread thd2(work, std::ref(thread_no1));
thd1.join();
thd2.join();
return 0;
}