mercredi 4 mars 2015

Using a shared pointer in a std::thread

I have a scenario where:




  1. I launch a new thread from within a dll that does some work.




  2. The dlls destructor could be called before the new thread finishes its work.




  3. If so I want to set a boolean flag in the destructor to tell the thread to return and not continue.




If I try the following then I find that because the destructor is called and MyDll goes out of scope then m_cancel is deleted and its value is unreliable (Sometimes false, sometimes true) so I cannot use this method.



bool m_cancel = false;
MyDll:~MyDll()
{
m_cancel = true;
}

//Function to start receiving data asynchronously
void MyDll::GetDataSync()
{
std::thread([&]()
{
SomeFunctionThatCouldTakeAWhile();

if( m_cancel == true )
return;

SomeFunctionThatDoesSomethingElse();
}
}


So I have looked at this example Replacing std::async with own version but where should std::promise live? where a shared pointer is used which can be accessed from both threads.


So I was thinking that I should:




  1. Create a shared pointer to a bool and pass it to the new thread that I have kicked off.




  2. In the destructor, change the value of this shared pointer and check it in the new thread.




Here is what I have come up with but I'm not sure if this is the proper way to solve this problem.



std::shared_ptr<bool> m_Cancel;

//Constructor
MyDll:MyDll()
{
m_Cancel = make_shared<bool>(false);
}
//Destructor
MyDll:~MyDll()
{
std::shared_ptr<bool> m_cancelTrue = make_shared<bool>(true);

m_Cancel = std::move(m_cancelTrue);
}

//Function to start receiving data asynchronously
void MyDll::GetDataSync()
{
std::thread([&]()
{
SomeFunctionThatCouldTakeAWhile();

if( *m_Cancel.get() == true )
return;

SomeFunctionThatDoesSomethingElse();
}
}


If I do the above then the if( *m_Cancel.get() == true ) causes a crash (Access violation)




  1. Do I pass the shared pointer by value or by reference to the std::thread??




  2. Because its a shared pointer, will the copy that the std::thread had still be valid even MyDll goes out of scope??




How can I do this??


Aucun commentaire:

Enregistrer un commentaire