Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write your own condition variable using atomic primitives

Tags:

c++

I need to write my own implementation of a condition variable much like pthread_cond_t.

I know I'll need to use the compiler provided primitives like __sync_val_compare_and_swap etc.

Does anyone know how I'd go about this please.

Thx

like image 640
ScaryAardvark Avatar asked Dec 07 '22 01:12

ScaryAardvark


1 Answers

Correct implementation of condition variables is HARD. Use one of the many libraries out there instead (e.g. boost, pthreads-win32, my just::thread library)

You need to:

  • Keep a list of waiting threads (this might be a "virtual" list rather than an actual data structure)
  • Ensure that when a thread waits you atomically unlock the mutex owned by the waiting thread and add it to the list before that thread goes into a blocking OS call
  • Ensure that when the condition variable is notified then one of the threads waiting at that time is woken, and not one that waits later
  • Ensure that when the condition variable is broadcast then all of the threads waiting at that time are woken, and not any threads that wait later.
  • plus other issues that I can't think of just now.

The details vary with OS, as you are dependent on the OS blocking/waking primitives.

like image 169
Anthony Williams Avatar answered Dec 09 '22 15:12

Anthony Williams