官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 东乌珠穆沁旗| 大安市| 微山县| 云南省| 元江| 岢岚县| 红原县| 清水县| 恩施市| 汽车| 武宁县| 崇州市| 哈巴河县| 新野县| 叶城县| 普陀区| 宜丰县| 望谟县| 西乌珠穆沁旗| 乐业县| 民丰县| 唐海县| 清徐县| 松桃| 南华县| 增城市| 南漳县| 平阴县| 海兴县| 五寨县| 商南县| 元阳县| 瑞昌市| 买车| 乌苏市| 桂阳县| 翼城县| 济南市| 昭通市| 桦甸市| 平江县|