下面的代码是c++并发操作中的一个作用域线程示例。但是我在xcode5.1中运行这个示例时有一个问题,因为Scoped_thread t是在其析构函数中加入的,所以t的析构函数在线程main()的末尾运行?因此,无论我有多长时间的主()线程睡眠,主的输出在t的输出之前,但答案不是吗?有人能帮我解释一下吗?
#include <iostream>
#include <algorithm>
#include <thread>
#include <chrono>
using namespace std;
struct Scoped_thread
{
std::thread sthread;
Scoped_thread(std::thread tmp):sthread(std::move(tmp))
{
if (!sthread.joinable())
{
cout<<"error on contructor a scoped thread"<<endl;
}
}
~Scoped_thread()
{
sthread.join();
}
Scoped_thread(Scoped_thread& tmp) = delete;
Scoped_thread& operator =(const Scoped_thread& tmp) = delete;
};
void hello_scoped_thread()
{
cout<<"this is scoped thread output"<<endl;
}
int main()
{
Scoped_thread t((std::thread(hello_scoped_thread)));
//std::this_thread::sleep_for(std::chrono::seconds(10));
cout<<"this is in main thread"<<endl;
return 0;
}编辑+:我想知道主线程(已知的t线程)何时被连接,main何时在编译器解析代码时破坏t? /,还是像这样?
发布于 2014-08-04 07:49:51
线程是异步运行的,因此不应该过多地关注线程和main之间的操作顺序。操作通常会尽可能快地完成,所以当一个线程等待时,其他线程就可以继续了。
作用域线程类只是注意主线程等待直到新线程通过连接在作用域的末尾(即main()函数的结尾)结束。
https://stackoverflow.com/questions/25113782
复制相似问题