c ++ 11 multithreaded record 2: thread management

No thread calls join and detach

thread object must call join or detach, otherwise the program will terminate
For example:

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

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

Before might also join / detach throw an exception resulting in no call join / detach normal

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

The code above where the block was thrown in the lead to join has not been called

Solution

A first solution is to add try-catch block

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

The second method uses RAII, the thread objects into a custom type classT, the attempt to call the destructor join classT's / detach

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

Guess you like

Origin www.cnblogs.com/ChenLambda/p/11724976.html