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
原文链接: https://www.cnblogs.com/qwsdcv/p/13679409.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/202841
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!