std::atomic对int, char, bool等数据结构进行原子性封装,在多线程环境中,对std::atomic对象的访问不会造成竞争-冒险。利用std::atomic可实现数据结构的无锁设计。
Atomic.h
// std::atomic
class CAtomic
{
public:
CAtomic() { m_Foo = 0; }
~CAtomic() {}
void Run();
int Func(int x, int y) {}
void Add_Foo();
void Sub_Foo();
private:
std::atomic<int> m_Foo;
std::atomic_flag lock = ATOMIC_FLAG_INIT;
};
Atomic.cpp
void CAtomic::Run()
{
printf("========std::atomic==========\n");
// std::atomic_flag是一个原子的布尔类型,可支持两种原子操作
std::atomic_flag lock1 = ATOMIC_FLAG_INIT;
printf("[std::auto] atomic_flag: %d \n", lock1.test_and_set());
// std::atomic对int, char, bool等数据结构进行原子性封装
std::thread th2 = std::thread(std::bind(&CAtomic::Add_Foo, this));
std::thread th1 = std::thread(std::mem_fn(&CAtomic::Sub_Foo), this);
th1.join();
th2.join();
}
void CAtomic::Add_Foo()
{
int nCNt = 5;
while (nCNt-- )
{
m_Foo++;
//m_Foo = m_Foo + 4;
while (lock.test_and_set()); //如果atomic_flag对象被设置,则返回true; 如果atomic_flag对象未被设置,则设置之,返回false
printf("[std::auto] atomic<int> add: %d \n", m_Foo);
lock.clear(); //清楚atomic_flag对象
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void CAtomic::Sub_Foo()
{
int nCNt = 5;
while (nCNt--)
{
m_Foo--;
// m_Foo = m_Foo - 1;
while (lock.test_and_set());
printf("[std::auto] atomic<int> sub: %d \n", m_Foo);
lock.clear();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
调用:
int main()
{
//测试std::atomic
std::shared_ptr<CBase> pAtomic = std::make_shared<CAtomic>();
pAtomic->Run(); Tab;
return 0;
}
运行结果: