jeudi 19 mars 2020

Setting a variable inside a std::thread, accessible from the caller thread

From my main thread, I am starting an std::thread as follows.

   bool m_threadCompleted = false;
   std::function<void(bool)> downloadCompleted = [&m_threadCompleted](bool completed) {
        m_threadCompleted = completed;
   };
   m_threads.push_back(std::thread(&MyModule::doRun, this, true, downloadCompleted));

If I call the function downloadCompleted with the value true inside the execution context of the thread and then check that value in the main thread, will it work? (as follows)

  /*Main Process*/
  if(m_threadCompleted) {
       //do cleanup
  }

I have tried this and it doesn't seem to work. Can someone explain why this is, and what is a better way to acheive this?

Aucun commentaire:

Enregistrer un commentaire