Lab CondVariable
Lab CondVariable
Yu Chengye
[email protected]
Lab eight
In this lab, you will learn how to use condition variables in pthread library to
implement wakeup-enabled multi-threading programs. In particular, we will use
the following functions:
pthread_create
pthread_exit
pthread_mutex_lock
pthread_mutex_unlock
pthread_cond_init()
pthread_cond_wait()
pthread_cond_signal()
Condition Variable
int done = 0;
void thr_exit() {
pthread_mutex_lock(&m);
done = 1;
pthread_cond_signal(&c);
pthread_mutex_unlock(&m);
}
void thr_join() {
pthread_mutex_lock(&m);
while (done == 0) // prevent spurious wakeup
pthread_cond_wait(&c, &m);
pthread_mutex_unlock(&m);
}
Example
thr_join();
printf("parent: end\n");
return 0;
}
Q1: pthread_cond_wait(&c, &m)
pthread_cond_wait(pthread_cond_t* C, pthread_mutex_t* M)
{
put this thread into wakeup queue of condtion var C.
pthread_mutex_unlock(M);
sleep();
pthread_mutex_lock(M);
take this thread out of wakeup queue of condition var C.
}
Q2: while (done == 0)
Spurious wakeup !
Any questions?