waiting thread until a condition has been occurred

前端 未结 4 1124
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 10:22

I want to wait one thread of 2 thread that executed in a Simultaneous simulator until a condition has been occurred, may be the condition occurred after 1000 or more cycles

4条回答
  •  醉梦人生
    2020-12-05 10:51

    You need conditional variables.

    If your compiler supports std::conditional introduced by C++11, then you can see this for detail:

    • std::condition_variable (C++11 threads)

    If your compiler doesn't support it, and you work with win32 threads, then see this:

    • Condition Variables (Win32 threads)

    And here is a complete example.

    And if you work with POSIX threads, then see this:

    • Condition Variables (POSIX threads)

    You can see my implementation of conditional_variable using win32 primitives here:

    • Implementation of concurrent blocking queue for producer-consumer

    Scroll down and see it's implementation first, then see the usage in the concurrent queue implementation.

    A typical usage of conditional variable is this:

    //lock the mutex first!
    scoped_lock myLock(myMutex); 
    
    //wait till a condition is met
    myConditionalVariable.wait(myLock, CheckCondition);
    
    //Execute this code only if the condition is met
    

    whereCheckCondition is a function (or functor) which checks the condition. It is called by wait() function internally when it spuriously wakes up and if the condition has not met yet, the wait() function sleeps again. Before going to sleep, wait() releases the mutex, atomically.

提交回复
热议问题