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
posted @ 2020-09-16 15:34  开学五年级了  阅读(598)  评论(0编辑  收藏  举报