Question

tbb::tbb_thread*                    m_tbbTimerThread;
m_tbbTimerThread = new tbb::tbb_thread(&sFirstTimerBlocked, this);

// Above thread is spawned.

Later I want to deleted thread in different function. I am doing it as below.

if(m_tbbTimerThread != NULL ) 
{
    delete m_tbbTimerThread;
}

m_tbbTimerThread = NULL;

Is this right way of doing.

Thanks!

Was it helpful?

Solution

Depends on your notion of 'right'.

In general it's a bad idea to destroy a thread object that is still attached to a running thread. C++11's std::thread will reward you with a call to std::terminate for attempting this. TBB is a lot more forgiving (the thread is simply detached upon destruction), but that does not make the underlying problem go away.

In particular, you might lose your last chance of guaranteeing a clean shutdown. If your process exits, how can you guarantee that the detached thread is not in the middle of writing something to the disk? How can you guarantee that it does not hold on to some persistent handles that will leak if the thread dies without explicitly cleaning them up? Mind you, RAII will probably not kick in if the thread is killed because of the parent process dying. In general, detaching a thread is very problematic for all but the most trivial threads.

So arguably a 'righter' way to shutdown would be:

if(m_tbbTimerThread != NULL ) 
{
    if(m_tbbTimerThread->joinable()) {
        <notify the thread to shutdown>
        m_tbbTimerThread->join();
    }
    delete m_tbbTimerThread;
}

For non-blocking threads, a single atomic flag might already be enough to implement the shutdown notification.

As with every rule, there is an exception: Sometimes you can shift the monitoring responsibilities to another object, in which case it might be fine to detach the thread. For example, a C++11 std::async call spawns a new thread and returns a future that will become ready once the thread has finished. Waiting on the future serves the same purpose as joining the thread, so there is no need for async to return an explicit thread object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top