C/C++教程

c++新特性之std::atomic

本文主要是介绍c++新特性之std::atomic,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

std::atomic为C++11封装的原子数据类型, 支持多种类型数据的原子操作,以下是atomic支持的数据类型,摘自http://www.cplusplus.com/reference/atomic/。

#include <atomic>
#include <thread>
#include <list>
std::atomic_int g_iCount = 100;

void threadfunc1()
{
while (g_iCount > 0)
{
printf("threadfunc1 g_iCount:%d\r\n", --g_iCount);
}
}

void threadfunc2()
{
while (g_iCount > 0)
{
printf("threadfunc2 g_iCount:%d\r\n", --g_iCount);
}
}

int main(int argc, char** argv)
{
thread t1(threadfunc1);
thread t2(threadfunc1);
thread t3(threadfunc2);
thread t4(threadfunc2);

t1.join();
t2.join();
t3.join();
t4.join();

return 0;
}

 

以上初始化4线程,用来运行int类型的g_iCount的递减操作,未出现任何数据错误的情况。

 

这篇关于c++新特性之std::atomic的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!