#include <thread>
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
// 參考鏈接:https://blog.csdn.net/Kaiwii/article/details/8461277
/*
* @desc pthread_key_t
* 線程特有變量,對進程來看只有一個變量,但是在線程中,該變量的數據是完全獨立的。
* @method
* pthread_key_create(&threadData, NULL);
* 作用:創建線程變量
* 參數說明:
* (1)第一個參數爲待創建的pthread_key_t地址
* (2)第二個參數爲線程變量退出的時候調用的清理函數,函數原型爲void (void*),其中void行爲pthread_key_t中存儲的變量
* 注意:特別注意該函數只能在進程中調用一次,不可每個線程都調用。
* int pthread_setspecific(pthread_key_t key, const void *value);
* 作用:將線程獨立變量設置到pthread_key_t類型變量中,注意第二個參數爲void*,可以設置任何類型的值
* 參數說明:
* (1)第一個參數爲存儲數據的pthread_key_t類型變量
* (2)第二個參數爲待存儲的數據的指針,理論上可以存儲任何類型的指針
* void *pthread_getspecific(pthread_key_t key);
* 作用:取出pthread_key_t中存儲的變量地址
* 參數說明:
* (1)第一個參數爲待取出來的pthread_key_t類型變量,返回值爲其存儲的變量指針。
*/
static pthread_key_t threadData;
void ChangeThreadData(int id) {
// 初始化
//printf("%lld id:%d\n", std::this_thread::get_id(), id);
pthread_setspecific(threadData, &id);
std::this_thread::sleep_for(std::chrono::seconds(3));
printf("%lld id:%d thread_data:%d\n", std::this_thread::get_id(), id, *((int*)pthread_getspecific(threadData)));
// printf("%lld \n", std::this_thread::get_id());
// printf("id:%d\n", id);
// printf("thread_data:%d\n", *((int*)pthread_getspecific(threadData)));
}
int main() {
std::vector<std::thread> threadVec;
// 特別注意pthread_key_t 只能在當前進程初始化的時候create一次,若每個線程中都create一次,會導致程序coredump.
pthread_key_create(&threadData, NULL);
for (int i = 0; i < 10; i++)
threadVec.emplace_back(ChangeThreadData, i);
for (auto& th : threadVec) {
th.join();
}
}
以示例方式記錄pthread_key_t
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.