Are there any known algorithms for simulating pthread_cond_wait when using semaphores instead of mutexes?
Are there any known algorithms for simulating pthread_cond_wait when using semaphores instead of mutexes?
The only difference between using a semaphore and pthread_cond_wait is that signaling a semaphore will allow the next thread through even if there is not a thread currently blocking. pthread_cond_signal does nothing if no thread is waiting on a call to pthread_cond_wait.
So instead of just calling sem_post instead of pthread_cond_signal, you have to do something like this:
The calls to lock() and unlock() are just locking and unlock a simple mutex. This can also be implemented with a semaphore as brewbuck described.Code:// blocking side lock(); thread_blocking++; unlock(); sem_wait(); lock(); thread_blocking--; unlock(); // signal side lock() if(thread_blocking) sem_post(); unlock();
bit∙hub [bit-huhb] n. A source and destination for information.