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

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.

主站蜘蛛池模板: 乡城县| 黑河市| 开平市| 简阳市| 息烽县| 马山县| 延吉市| 广德县| 梨树县| 温宿县| 淅川县| 陈巴尔虎旗| 宁安市| 大同市| 兴宁市| 岢岚县| 清镇市| 股票| 钟祥市| 西贡区| 本溪市| 望奎县| 信阳市| 长寿区| 桑日县| 甘孜| 三门县| 南部县| 玛多县| 宜君县| 望都县| 沭阳县| 公主岭市| 海盐县| 宜昌市| 防城港市| 邮箱| 岱山县| 巴马| 库伦旗| 台湾省|