在C++中,thread_local關鍵字用于聲明一個線程局部變量,這意味著每個線程都有其自己的變量副本
class MyClass {
public:
~MyClass() {
// 清理操作
}
};
thread_local MyClass myObject;
std::thread_local_storage:C++17引入了std::thread_local_storage,它允許你更細粒度地控制線程局部變量的存儲。你可以使用std::destroy_all函數來銷毀所有線程局部變量的實例。#include <iostream>
#include <thread>
#include <thread_local_storage>
struct MyClass {
~MyClass() {
std::cout << "MyClass destroyed in thread " << std::this_thread::get_id() << std::endl;
}
};
std::thread_local_storage<MyClass> myObjectStorage;
void threadFunction() {
MyClass& myObject = myObjectStorage.construct<MyClass>();
// 使用 myObject
}
int main() {
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
std::destroy_all(myObjectStorage.get_storage());
return 0;
}
在這個例子中,我們使用std::thread_local_storage來存儲MyClass的實例。當線程結束時,MyClass的實例會被銷毀,從而完成清理操作。注意,我們需要調用std::destroy_all來銷毀所有線程局部變量的實例。