boost::thread编程-线程本地存储

19 篇文章 1 订阅
7 篇文章 1 订阅
有时候函数使用了局部静态变量或全局静态变量,因此不能用于多线程环境,因此无法保证静态变量在多线程重入时的正确操作。
boost::thread库使用thread_specific_ptr实现了可移植的线程本地存储机制(thread local storage,或者是thread specific storage,简称tss),使这样的变量用起来就像每个线程独立拥有,可以简化多线程应用,提高性能。

thread_specific_ptr的用法示例如下:

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>

boost::mutex io_mu;//io读写锁

void printing()
{
	boost::thread_specific_ptr<int> pi;//线程本地存储一个整数
	pi.reset(new int());//直接用reset()赋值

	for(int i=0;i<5;++i)
	{
		++ (*pi);

		boost::mutex::scoped_lock lock(io_mu);
		std::cout<<"thread id:"<<boost::this_thread::get_id()<<" print value(*pi)="<<*pi<<std::endl;
	}	
}

int _tmain(int argc, _TCHAR* argv[])
{
	boost::thread thrd1(printing);
	boost::thread thrd2(printing);
	thrd1.join();
	thrd2.join();
	getchar();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值