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的递减操作,未出现任何数据错误的情况。