简体   繁体   中英

std::condition_variable::notify_all() guarantees

Suppose there are N waiting threads (readers) on a condition variable which are notified by another thread (producer). Now all the N readers will proceed by trying to own the unique_lock they refers to, one at a time. Now suppose the producer wants to lock the same unique_lock again, for some reasons, before any of those woken readers even started own the lock. By the standard, is there any guarantee that the producer will successfully (try to) enter its critical section only after all the notified readers have started their locking step?

There is no guarantee about scheduling, other than the rather fuzzy one given at §1.10 paragraph 2:

Implementations should ensure that all unblocked threads eventually make progress. [ Note: Standard library functions may silently block on I/O or locks. Factors in the execution environment, including externally-imposed thread priorities, may prevent an implementation from making certain guarantees of forward progress. end note ]

If you want to make sure no reader acquires the lock before the producer, you can simply acquire the lock before notifying.

If you want to make sure the producer can only acquire the lock after all the readers are done with it you need some more complex synchronization, possibly involving some kind of counter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM