__thread

__thread

__thread修饰的变量,在每个线程中都有一份独立实体,每个线程互不干扰,可以修饰全局性且值可能改变的变量

#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
// static __thread int i = 1;	// 修饰static变量
__thread int i = 1;	// 修饰全局变量

void* work1(void* arg) {
	cout << ++i << endl;	// 输出2
	return NULL;
}

void* work2(void* arg) {
	sleep(1);	// 等待线程work1修改i之后,继续work2	
	cout << ++i << endl;	// 输出2
	return NULL;
}

int main() {
	pthread_t pid1, pid2;
	pthread_create(&pid1, NULL, work1, NULL);
	pthread_create(&pid2, NULL, work2, NULL);
	pthread_join(pid1, NULL);
	pthread_join(pid2, NULL);

	cout << i << endl;	// 输出1

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值