简体   繁体   English

如何检查std :: thread是否有效

[英]How to check if std::thread is valid

I got a class object, which only needs in some cases to start a thread. 我有一个类对象,在某些情况下只需要启动一个线程。 In the destructor it would be convenient for me to know whenever or not there is/was a thread. 在析构函数中,无论何时有线程都可以方便地知道。 The question is, how do I detected if a std::thread object is or was a valid thread. 问题是,如何检测std :: thread对象是否是有效线程。

class MyClass
{
public:
   ~MyClass()
    {
       // Attention pseudocode!!!!!
       if(mythread is a valid object)
           mythread.join();

       if(mythread was a valid object in its lifetime)
           Do some stuff
    }

    void DoSomeStuff()
    {
      // May or may not create a thread
    }
private:
   std::thread mythread;
};

I believe you're looking for the joinable function: 我相信你正在寻找joinable功能:

~MyClass()
{
    if (t.joinable()) { t.join(); }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM