Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to wait for a variable in a multithreaded application

I would like to do something like the below for a multi-threaded program:

// wait for variable to become true but don't hog resources  
// then re-sync queues  

Is something like this a good solution?

while (!ready) {
    Thread.Sleep(250); // pause for 1/4 second;
};
like image 753
T.T.T. Avatar asked Jan 13 '10 20:01

T.T.T.


2 Answers

No, this is not a good solution. First it might sleep too long. Second it's easy for threads to get into lockstep. Here's couple of links to MSDN articles on proper synchronization techniques:

  • Conditional variables
  • Events
like image 140
Nikolai Fetissov Avatar answered Oct 26 '22 10:10

Nikolai Fetissov


Here's how you do it using boost:

boost::condition_variable condvar;
boost::mutex mutex;
bool finished1 = false;
bool finished2 = false;

void longComputation1()
{
    {
        boost::lock_guard<boost::mutex> lock(mutex);
        finished1 = false;
    }
    // Perform long computation
    {
        boost::lock_guard<boost::mutex> lock(mutex);
        finished1 = true;
    }
    condvar.notify_one();
}

void longComputation2()
{
    {
        boost::lock_guard<boost::mutex> lock(mutex);
        finished2 = false;
    }
    // Perform long computation
    {
        boost::lock_guard<boost::mutex> lock(mutex);
        finished2 = true;
    }
    condvar.notify_one();
}

void somefunction()
{
    // Wait for long computations to finish without "spinning"
    boost::lock_guard<boost::mutex> lock(mutex);
    while(!finished1 && !finished2)
    {
        condvar.wait(lock);
    }

    // Computations are finished
}

For the sake of brevity, I didn't include the thread spawning code.

The boost::lock_guard uses the RAII idiom to automatically unlock the mutex when the lock object goes out of scope. Very useful for preventing deadlocks in case of exceptions.

I find condition variables less error prone than Microsoft's Event objects. If you use boost.Thread, you'll have the added benefit of cross-platform potability.

like image 43
Emile Cormier Avatar answered Oct 26 '22 08:10

Emile Cormier