简体   繁体   中英

C++ library version of upcoming C++20 wait/notify

C++20 is introducing https://en.cppreference.com/w/cpp/atomic/atomic/wait and https://en.cppreference.com/w/cpp/atomic/atomic/notify_one , which introduces atomic waiting and notification functionality.

I'd like to use this but my compiler doesn't support it yet.

  1. Are there any reliable library implementations of this functionality?
  2. I'm envisioning using this functionality in lock-free producer-consumer situation where the consumer goes to sleep and is woken up when there's something to consume. There are no mutexes in my current implementation. Am I correct that such wait/notify functionality would allow me to do what I want to do (ie, let my consumer thread go to sleep and let the producer efficiently wake it up without acquiring a mutex (something that would be necessary, I believe, with a condition variable).
  3. Actually, is there an even better way to do this that I'm not currently thinking of?

Are there any reliable library implementations of this functionality?

You can use Boost.Atomic if your compiler's standard library implementation does not support it yet.

Am I correct that such wait/notify functionality would allow me to do what I want to do (ie, let my consumer thread go to sleep and let the producer efficiently wake it up without acquiring a mutex (something that would be necessary, I believe, with a condition variable).

Correct.

Actually, is there an even better way to do this that I'm not currently thinking of?

Atomic wait is a good way. You may also want to use it the best way:

  • Avoid notifying when you know that the other party does not wait. Some implementations would check it for you, some wouldn't.
  • Use the same atomic size as underlying OS primitive uses. This means using 32-bit queue counters on Linux, where the native primitive is futex , and it takes 32-bit integer. On Windows, WaitOnAddress can take any size of 8, 16, 32, or 64. On other systems consider their implementation of atomic wait.

As other good way you can consider C++20 semaphores.

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