Do I need to synchronize std::condition_variable/condition_variable_any::notify_one

后端 未结 2 1240
太阳男子
太阳男子 2020-12-16 14:03

Do I need to synchronize std::condition_variable/condition_variable_any::notify_one?

As far as I can see, if lost of notifications is acceptable - it is

2条回答
  •  隐瞒了意图╮
    2020-12-16 14:47

    (1) I don't see any reason that signalling a condition variable has to be guarded by a mutex, from a data-race stand-point. Obviously, you have the possibility of receiving redundant notifications or losing notifications, but if this is an acceptable or recoverable error condition for your program, I don't believe there's anything in the standard that will make it illegal. The standard, of course, won't guard you against race conditions; it's the programmer's responsibility to make sure that race conditions are benign. (And, of course, it is essential that the programmer not put any "data races", which are defined very specifically in the standard but don't apply directly to synchronization primitives, or undefined behavior is summoned.)

    (2) I can't answer a question like this about the internal implementation of a standard library facility. It is, of course, the vendor's responsibility to provide library facilities that work correctly and meet the specification. This library's implementation may have some internal state that requires mutual exclusion to avoid corruption, or it may perform locking in order to avoid lost or redundant notifications. (Just because your program may tolerate them, doesn't mean arbitrary users of the library can, and in general I expect they can't.) It would just be speculation on my part what they're guarding with this mutex.

    (3) condition_variable_any is made to work on any lock-like object, while condition_variable is designed specifically to work with unique_lock. The latter is probably easier to implement and/or more performant than the former, since it knows specifically which types it is operating on and what they require (whether they're trivial, whether they fit in a cache line, whether they map directly to a specific platform's set of syscalls, what fences or cache coherence guarantees they imply, etc.), while the former provides a generic facility for operating on lock-ish objects without being stuck specifically with the constraints of std::mutex or std::unique_lock<>.

提交回复
热议问题