最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Why doesn't cause every thread the constructor to run when the class is initialised with a thread_local? - Stack O

programmeradmin0浏览0评论

I have a thread_local variable, which should initialize a class in every thread, but the constructor isn't called, when the threads are opened. The constructor is only called, when I place the instance somewhere in the the code like in my example:

#include <iostream>
#include <thread>
#include <future>

thread_local int val = 0;
                        
class MyClass {
    public:
        MyClass() {
            std::cout << "ctor" << std::endl;
        }

        void task() {
            std::cout << "Hello" << std::endl;
        }
};

thread_local MyClass myClass;
                            
void threadMain() {
    std::cout << val << std::endl;
}

int main() {
    val = 15;
    std::cout << val << std::endl;
    myClass;//here is the variable placed
    std::thread thread1(threadMain);
    thread1.join();
    auto a = std::async(std::launch::async, threadMain);
    a.wait();
    return 0;
}

the output with the g++ compiler is:

15
ctor
0
0

Can somebody please explain, what happens here?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论