✅ The verified answer to this question is available below. Our community-reviewed solutions help you understand the material better.
Recall the code below from class where we used a condition variable to make sure the child runs before the parent prints. Why did we include the int variable done if signalling and waiting is done automatically with condition variables?
int done = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void thr_exit() {
Pthread_mutex_lock(&m);
done = 1;
Pthread_cond_signal(&c);
Pthread_mutex_unlock(&m);
}
void *child(void *arg) {
printf("child");
thr_exit();
return NULL;
}
void thr_join() {
Pthread_mutex_lock(&m);
while (done == 0)
Pthread_cond_wait(&c, &m);
Pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[]) {
printf("parent: begin");
pthread_t p;
Pthread_create(&p, NULL, child, NULL);
thr_join();
printf("parent: end");
return 0;
}
Get Unlimited Answers To Exam Questions - Install Crowdly Extension Now!