- 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.
推薦閱讀
- Mastering OpenCV Android Application Programming
- HTML5 移動Web開發(fā)從入門到精通(微課精編版)
- Java Web及其框架技術
- 數據庫系統(tǒng)原理及MySQL應用教程
- 基于Swift語言的iOS App 商業(yè)實戰(zhàn)教程
- Bootstrap 4:Responsive Web Design
- Serverless架構
- Python編程從0到1(視頻教學版)
- Building Wireless Sensor Networks Using Arduino
- 零基礎學C語言程序設計
- IPython Interactive Computing and Visualization Cookbook
- Android編程權威指南(第4版)
- Java程序設計
- Learning NHibernate 4
- Access 2016數據庫應用與開發(fā):實戰(zhàn)從入門到精通(視頻教學版)