有時候函數使用了局部靜態變量或全局靜態變量,因此不能用于多線程環境,因此無法保證靜態變量在多線程重入時的正確操作。
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;
}
~~~