condition_variable / shared variable / Signalling
Thread1 notifies/signals Thread2 for condition. Then thread2 starts
executes, until then thread2 is blocked
Advantages?
1. Avoids busy waiting, ie done by spinlock
2. Similar to [Semaphores]
POSIX
#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespace std;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *fun1(void* arg) {
//pthread_mutex_lock(&mutex);
cout << "Thread1 waiting on condition\n";
//pthread_cond_wait() might provide unexepected result without mutex
pthread_cond_wait(&cond, &mutex);
cout << "Condition satisfied\n";
//pthread_mutex_unlock(&mutex);
}
void *fun2(void* arg) {
sleep(1);
cout << "Thread2 signalled the condition\n";
pthread_cond_signal(&cond);
}
int main(){
pthread_t tid1,tid2;
pthread_create(&tid1, 0, fun1, 0);
pthread_create(&tid2, 0, fun2, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
$ ./a.out
Thread1 waiting on condition
Thread2 signalled the condition
Condition satisfied
Ping Pong Game
| POSIX pthread | C++11 (2 threads. 1 producer 1 consumer) | C++11 (4 threads. 2 producers 2 consumers) | |
|---|---|---|---|
| Code |
|
thread1 prints ping and then signal on condition variable. thread2 waits for signal and then only prints pong notify_one() notify 1 of threads waiting on condition variable (test). |
thread1,2 prints ping and then signal on condition variable. thread3,4 waits for signal and then only prints pong notify_all() notify all of threads waiting on condition variable (test).
|