#include <iostream>
#include <thread>
#include <atomic>
int cnt=0;
class MyLock
{
private:
std::atomic_flag lk = ATOMIC_FLAG_INIT;;
public:
MyLock() {};
void lock();
void unlock();
};
void MyLock::lock()
{
while (lk.test_and_set())
{
cnt++;
}
};
void MyLock::unlock()
{
lk.clear();
};
MyLock mlk;
int sum = 0;
void fun()
{
for (int i = 0; i < 100000; ++i)
{
mlk.lock();
sum += 1;
mlk.unlock();
}
}
int main()
{
std::thread t1(fun);
std::thread t2(fun);
t1.join();
t2.join();
std::cout << "sum = " << sum << std::endl;
}
#编译要用 g++ -pthread -std=c++11 atomic.cc