I am currently using shared pointer with QThreadPool for a multi-threaded application. However I am experiencing crashes when the threads finishes computation.
Assume Class A is inherited from QRunnable and when passing in the shared pointer as argument, it updates its class variable. Here is the code:
for(int i=0;i<1000;i++)
{
boost::shared_ptr<VariableType> variable = boost::make_shared<VariableType>();
variable->Update_One_InternalVariable(1); // just updating a class variable inside VariableType
Class* A = new Class(variable);
A->setAutoDelete(true);
QThreadPool::globalInstance()->start(A);
m_thread_count++;
if(m_thread_count >0 && m_thread_count %4== 0)
{
QThreadPool::globalInstance()->waitForDone(); // crashes after all threads finished here
}
}
QThreadPool::globalInstance()->waitForDone();
The crashes happened soon after 4 threads has been executed and ended. I assume the crash happens when QThreadPool tries to delete these threads? Can someone point out if I have done anything wrong here with shared pointers in multi-threaded environment?
shared_ptr
is not thread-safe, as in accessing the same instance from multiple threads is not allowed. However, using two different instances of shared_ptr
that both point to the same object is thread-safe, as long as that object itself is thread-safe. See also the documentation
So if you store the shared_ptr
as a reference in Class
, that might crash. Make a copy of the shared_ptr
instead.