atomic c++ y原子变量 替换锁代码

#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

有时候,不小心知道了一些事,才发现自己所在乎的事是那么可笑。
原文地址:https://www.cnblogs.com/axjlxy/p/15266269.html