C++ thread_local
thread_local 变量调用其类型的拷贝构造函数,为每一个线程创建一个副本。
#include <stdio.h>
#include <thread>
#include <string.h>
class STR{
public:
char *s;
STR(const STR& str){
STR(str.s);
}
STR(const char*p){
s = new char[strlen(p)];
strcpy(s,p);
}
~STR(){
delete[] s;
s=nullptr;
}
};
thread_local STR v("good");
void fun2(){
printf("thread name: %d\t str:%s->pointer: %d\n",std::this_thread::get_id(), v.s, v.s);
}
int main(){
fun2();
std::thread a(fun2),b(fun2);
a.join();
b.join();
}
可能的输出
$ ./hello
thread name: 2040133440 str:good->pointer: 37555232
thread name: 2022766336 str:good->pointer: 1879050432
thread name: 2014373632 str:good->pointer: 1744832704