0
点赞
收藏
分享

微信扫一扫

C++(11):原子类型

落拓尘嚣 2022-05-01 阅读 57
c++

为了便于多线程编程,C++11引入了原子类型,可以保证对该类型变量的操作不会产生多线程的竞争:

#include <iostream>
#include <atomic>
#include <thread>
using namespace std;

atomic_int g_d{0};    //定义原子类型变量

void tFunc(int a)
{
	for(int i = 0; i < 100000000; ++i)
	{
		g_d++;        //对原子类型的操作,不会产生竞争
	}
}

int main(){
	thread t1(tFunc, 0);
	thread t2(tFunc, 0);
	t1.join();
	t2.join();
	cout<<g_d<<endl;
	return 0;
}

运行程序输出:
200000000
举报

相关推荐

0 条评论