- Mastering C++ Multithreading
- Maya Posch
- 195字
- 2021-07-15 17:34:03
Thread local storage (TLC)
With Pthreads, TLS is accomplished using keys and methods to set thread-specific data:
pthread_key_t global_var_key;
void* worker(void* arg) {
int *p = new int;
*p = 1;
pthread_setspecific(global_var_key, p);
int* global_spec_var = (int*) pthread_getspecific(global_var_key);
*global_spec_var += 1;
pthread_setspecific(global_var_key, 0);
delete p;
pthread_exit(0);
}
In the worker thread, we allocate a new integer on the heap, and set the global key to its own value. After increasing the global variable by 1, its value will be 2, regardless of what the other threads do. We can set the global variable to 0 once we're done with it for this thread, and delete the allocated value:
int main(void) {
pthread_t threads[5];
pthread_key_create(&global_var_key, 0);
for (int i = 0; i < 5; ++i)
pthread_create(&threads[i],0,worker,0);
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], 0);
}
return 0;
}
A global key is set and used to reference the TLS variable, yet each of the threads we create can set its own value for this key.
While a thread can create its own keys, this method of handling TLS is fairly involved compared to the other APIs we're looking at in this chapter.
推薦閱讀
- 多媒體CAI課件設計與制作導論(第二版)
- Expert C++
- Progressive Web Apps with React
- OpenCV實例精解
- SQL Server 2012數據庫技術及應用(微課版·第5版)
- Microsoft Dynamics 365 Extensions Cookbook
- 實戰Java程序設計
- Designing Hyper-V Solutions
- x86匯編語言:從實模式到保護模式(第2版)
- 匯編語言程序設計(第3版)
- QGIS:Becoming a GIS Power User
- Python Web數據分析可視化:基于Django框架的開發實戰
- Getting Started with Gulp
- 領域驅動設計:軟件核心復雜性應對之道(修訂版)
- Scratch·愛編程的藝術家