waiting for multiple condition variables in boost?

后端 未结 5 1608
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 09:36

I\'m looking for a way to wait for multiple condition variables. ie. something like:

boost::condition_variable cond1;  
boost::condition_variable cond2;

void wa         


        
5条回答
  •  星月不相逢
    2021-02-05 10:22

    As Managu already answered, you can use the same condition variable and check for multiple "events" (bool variables) in your while loop. However, concurrent access to these bool variables must be protected using the same mutex that the condvar uses.

    Since I already went through the trouble of typing this code example for a related question, I'll repost it here:

    boost::condition_variable condvar;
    boost::mutex mutex;
    bool finished1 = false;
    bool finished2 = false;
    
    void longComputation1()
    {
        {
            boost::lock_guard lock(mutex);
            finished1 = false;
        }
        // Perform long computation
        {
            boost::lock_guard lock(mutex);
            finished1 = true;
        }
        condvar.notify_one();
    }
    
    void longComputation2()
    {
        {
            boost::lock_guard lock(mutex);
            finished2 = false;
        }
        // Perform long computation
        {
            boost::lock_guard lock(mutex);
            finished2 = true;
        }
        condvar.notify_one();
    }
    
    void somefunction()
    {
        // Wait for long computations to finish without "spinning"
        boost::lock_guard lock(mutex);
        while(!finished1 && !finished2)
        {
            condvar.wait(lock);
        }
    
        // Computations are finished
    }
    

提交回复
热议问题