Search code examples
c++multithreadingoopthread-synchronization

Synchronization done by class destructors


I've got question about multithreading. I have a pretty big project and now I am writing some exe client to use all of that code. It involves multithreading and inter-process communication. I've got main which looks like this:

int main(int argc, char** argv)
{
std::unique_ptr<CommunicationWrapper> wrapper;

wrapper = std::make_unique<CommunicationWrapper>(argv[1]);
wrapper->run();

return 0;
}

Underneath there is a class which is doing inter-process communication which looks like this:

CommunicationEngine::CommunicationEngine()
 : m_processingLoop(std::async(std::launch::async, [this]() { processingLoop(); }))
{}

CommunicationEngine::~CommunicationEngine()
{
   m_processingLoop.wait();
}

//some long function that do a lot of stuff based on messages from anothre process
void CommunicationEngine::processingLoop() const 

This code work without a problem but I want to know if it is considered good practice and good design to do the synchronization (waiting) on call of destructor? What are possible pitfals of that approach?


Solution

  • RAII in general is a very useful idiom, it makes your code exception-safe and reduces risk of mistakes to appear during further modification.

    The main thing you should do - is to make sure your destructor will not throw.

    Regarding exception safety of std::future::wait - it's behavior is undefined when valid() == false before wait(), so you should rather check for that before calling it in desctructor.