I know this question sounds familiar and it might even be a stupid question but I wasn't able to find the solution to it.
So my question basically is, what happens when a parent_thread calls pthread_mutex_lock(&mutex) then calls pthread_cond_wait(&condition, &mutex) releasing the mutex, and then child_thread calls pthread_mutex_lock(&mutex) followed by pthread_cond_signal(&condition) and then pthread_mutex_unlock(&mutex). So this would mean that the mutex is unlocked and now if parent_thread attempts to call pthread_mutex_unlock(&mutex), it should result in undefined behavior, right ?
Example code:
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\n");
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\n");
pthread_t p;
pthread_create(&p, NULL, child, NULL);
thr_join();
printf("parent: end\n"); return 0;
}