1

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 (i.e., 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?
Kulluk007
  • 902
  • 2
  • 10
  • 24
  • I don't know anything about the actual implementation, but from a first look at the information given in your links I don't see how this would be any more efficient then using a condition variable. Isn't that what it will do? Only difference is that it detects a change in the value of `*this` instead of a change in the flag accompanying the `condition_variable`. – super Nov 29 '20 at 20:06
  • 1
    Related https://stackoverflow.com/questions/62859596/difference-between-stdatomic-and-stdcondition-variable-wait-notify-method – alex_noname Nov 29 '20 at 20:07

1 Answers1

0

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 (i.e., 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.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79