您的位置:首页 > 编程语言

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

2014-12-16 15:12 441 查看
有时候函数使用了局部静态变量或全局静态变量,因此不能用于多线程环境,因此无法保证静态变量在多线程重入时的正确操作。

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: