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

线程没有调用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;
}

猜你喜欢

转载自www.cnblogs.com/ChenLambda/p/11724976.html