condition_variable usage for signaling and waiting

If data race is not an issue, can I use std::condition_variable for starting (i.e., signaling) and stopping (i.e, wait) a thread for work?

For example:

std::atomic<bool> quit = false;
std::atomic<bool> work = false;
std::mutex mtx;

// if work, then do computation, otherwise wait on work (or quit) to become true
// thread reads: work, quit
void thread1()
{
   while ( !quit )
   {
      // limiting the scope of the mutex
      {
         std::unique_lock<std::mutex> lck(mtx);

         // I want here is to wait on this lambda
         cv.wait(lck, []{return work || quit; });
      }

      if ( work )
      {
         // work can become false again while working.
         // I want here is to complete the work
         // then wait on the next iteration.
         ComputeWork();
      }
   }
}

// work controller
// thread writes: work, quit
void thread2()
{
   if ( keyPress == '1' )
   {
      // is it OK not to use a mutex here?
      work = false;
   }
   else if ( keyPress == '2' )
   {
      // ... or here?
      work = true;
      cv.notify_all();
   }
   else if ( keyPress == ESC )
   {
      // ... or here?
      quit = true;
      cv.notify_all();
   }
}

Source: Windows Questions C++

LEAVE A COMMENT