C++(11):线程局部变量thread_local

325 篇文章 3 订阅 ¥299.90 ¥399.90

多线程中,每个线程都拥有自己的栈空间,但是对于全局变量、静态变量以及堆上空间,是共享于多个线程间的,这可以有效的在多个线程间共享数据,但也是多线程竞争的主要来源:

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

int g_d{0};

void tFunc(int a)
{
	for(int i = 0; i < a; ++i)
	{
		g_d++;
	}
	cout<<"thread:"<<a<<" g_d="<<g_d<<endl;
}

int main(){
	thread t1(tFunc, 60000);
	thread t2(tFunc, 80000);
	t1.join();
	t2.join();
	return 0;
}

两个线程分别对全局变量g_d进行操作,产生竞争
运行程序输出:
thread:60000 g_d=80419
thread:80000 g_d=98365

由于产生了线程竞争,因此此结果为随机的 

即使通过原子类型,也无法保证程序的运行结果:

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

atomic_int g_d{0};

void tFunc(int a)
{
	for(int i = 0
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风静如云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值