如何检查线程在C ++ 11及更高版本中是否已完成工作? [英] How to check if thread has finished work in C++11 and above?

查看:116
本文介绍了如何检查线程在C ++ 11及更高版本中是否已完成工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查线程在C ++ 11及更高版本中是否已完成工作?我正在阅读文档,并编写了以下代码:

How can I check if thread has finished work in C++11 and above? I have been reading the documentation and I have written the following code:

#include <iostream>
#include <thread>
void mythread() 
{
    //do some stuff
}
int main() 
{
  std::thread foo(mythread);  
  if (foo.joinable())
  {
    foo.join();
    //do some next stuff
  }
}

joinable仅告诉线程已开始工作,但是我想知道如何编写代码以检查线程是否已完成工作.

joinable tells only that the thread has started work, but I would like to know how to write code to check if the thread has finished work.

例如:

#include <iostream>
#include <thread>
void mythread() 
{
    //do some stuff
}
int main() 
{
  std::thread foo(mythread);  
  if (foo.finishedWork())
  {
    foo.join();
    //do some next stuff
  }
}

推荐答案

您可能想使用

You may want to use std::future, it provides higher level facilities where you can trivially check if the asynchronous computation is finished (aka ready): Example:

void mythread() {
    //do some stuff
}

template<typename T>
bool future_is_ready(std::future<T>& t){
    return t.wait_for(std::chrono::seconds(0)) == std::future_status::ready;
}

int main() 
{
    std::future<void> foo = std::async(std::launch::async, mythread);  
    if (future_is_ready(foo)){
        //do some next stuff
    }
}


另一方面,您可能会认为仅使用安全"(或原子)标志即可:


On the other hand, you may think simply using a "safe" (or atomic) flag works:

#include <iostream>
#include <thread>

std::atomic<bool> is_done{false};

void mythread() 
{
    //do some stuff
    ......
    is_done = true;
}
int main() 
{
  std::thread foo(mythread);  
  if (is_done)
  {
    foo.join();
    //do some next stuff
  }
  .....
  if(foo.joinable()) foo.join();
}

但是,它不起作用.您认为is_done = true是您在mythread()中所做的最后一件事;您可能在该范围内创建了一些具有自动存储持续时间的对象,并且由于这些对象以相反的构造顺序被破坏,因此在设置is_done之后,该线程中仍然会有一些工作"

But, it doesn't work. While you think is_done = true is the last thing you did in mythread(); You may have created some objects of automatic storage duration in that scope, and since such objects are destroyed in the reverse order of construction, there will still be "some work" in that thread after setting is_done.

这篇关于如何检查线程在C ++ 11及更高版本中是否已完成工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆