c++11标准库新增的thread类开始执行的时间?
ringa_lee
ringa_lee 2017-04-17 13:58:33
0
2
687

请问一下C++11中<thread>的,thread具体是什么时候执行赋予它的函数?
相关代码如下:

#include <iostream>
#include <thread>

void hello()
{
    std::cout << "Hello Current World!" << std::endl;
}

int main()
{
    std::thread t(hello);
    std::cout << "before: " << std::endl;
    t.join();
    std::cout << "after: "  << std::endl;
    return 0 ;
}

在windows平台上,IDE DEV-C++,编译器TDM-GCC 5.10,执行程序的结果有可能为



在linux(ubuntu)上,编译器g++ (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
执行程序执行了20~30遍一直是

也曾经尝试过直接把t.join()直接注释掉,两个平台都会崩溃,但是windows还是会先输出Hello Current World!之后崩溃,而linux只输出了before和after

看过cppreference里面相关的内容,好像是说在构造函数如果有赋予入口函数的话就会直接开始执行?不过linux里面好像是直到调用join函数或者detach函数才会开始执行?

ringa_lee
ringa_lee

ringa_lee

reply all(2)
阿神

If you pass in the routine to be executed in the constructor, the thread will start executing after the thread object is created. If you just create a thread object:

thread t;

Then this thread will not start until you assign a routine to this object. The reason why
crashes is that if the thread object does not join or detach before is destructed , then std::terminate will be called to terminate the program (you can look at the destructor implementation of thread), GCC Implementation of:

 ~thread()
    {
      if (joinable())
          std::terminate();
    }
Peter_Zhu

Add a line get char()

The child threads are not running, and the main thread has exited.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template