首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行中的c++并发线程执行示例

运行中的c++并发线程执行示例
EN

Stack Overflow用户
提问于 2014-08-04 07:36:58
回答 1查看 190关注 0票数 0

下面的代码是c++并发操作中的一个作用域线程示例。但是我在xcode5.1中运行这个示例时有一个问题,因为Scoped_thread t是在其析构函数中加入的,所以t的析构函数在线程main()的末尾运行?因此,无论我有多长时间的主()线程睡眠,主的输出在t的输出之前,但答案不是吗?有人能帮我解释一下吗?

代码语言:javascript
复制
#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? /,还是像这样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-04 07:49:51

线程是异步运行的,因此不应该过多地关注线程和main之间的操作顺序。操作通常会尽可能快地完成,所以当一个线程等待时,其他线程就可以继续了。

作用域线程类只是注意主线程等待直到新线程通过连接在作用域的末尾(即main()函数的结尾)结束。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25113782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档