最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

multithreading - Joining std threads in the destructor in C++ - Stack Overflow

programmeradmin2浏览0评论

I am creating two different threads which start running when an object gets created.

Is it ok to join these threads inside the destructor then as below?. Hence, wait for the threads to complete before fully destructing the object.

If the threads never terminate, then the object will never fully destruct when it is going out of scope and the main function will never return as in the case below.

Is this a problem, and is there a better recommended way to do this? Thanks.

MyClass::MyClass() 
{
    // t1, t2 are private member variables
    t1 = thread(&MyClass::producer, this); 
    t2 = thread(&MyClass::consumer, this); 
}

MyClass::~MyClass()
{
    //Join threads
    if (t1.joinable())
    {
        t1.join();
    }

    if (t2.joinable())
    {
        t2.join();
    }
}

int main()
{
    MyClass mc;
} 
发布评论

评论列表(0)

  1. 暂无评论