码迷,mamicode.com
首页 > 编程语言 > 详细

c++11多线程记录2:线程管理

时间:2019-10-23 11:56:50      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:return   wrap   code   int   main   raii   app   多线程   std   

线程没有调用join和detach

thread对象必须调用join或者detach,否则程序会终止
例如:

void func()
{
    std::cout << "hello, " << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::thread t(func);
    return 0;
}

也可能在join/detach之前抛出异常导致没有正常调用join/detach

void func()
{
    ......
}
int main()
{
    std::thread t(func);
    ......
    where (......)
    {    
        ......
        // 这里抛出异常
    }
    ......
    t.join();
    return 0;
}

上面这段代码在where块里抛出异常导致join没有被调用

解决方法

第一种解决方法是加上try-catch块

......
try {
    where () { ...... }
} catch (......) {
    if (t.joinable())
        t.join();
    throw;
}
......
t.join();
......

第二种方法使用RAII,将thread对象放到自定义类型classT中,在classT的析构方法里尝试调用join/detach

class Wrapper
{
public:
    ......
    ~Wrapper() { if (m_t.joinable()) m_t.join(); }
    ......
private:
    std::thread m_t;
}

c++11多线程记录2:线程管理

标签:return   wrap   code   int   main   raii   app   多线程   std   

原文地址:https://www.cnblogs.com/ChenLambda/p/11724976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!