Last active
November 7, 2023 12:15
-
-
Save alexklibisz/7cffdfe90c97986f8393 to your computer and use it in GitHub Desktop.
A simple example for using pthread_cond_wait() and pthread_cond_signal() with mutexes and conditional variables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <signal.h> | |
/* compile with gcc -pthread lockwait.c */ | |
pthread_cond_t cv; | |
pthread_mutex_t lock; | |
void *thread(void *v) { | |
printf("Locking and waiting. Type unlock to unlock me.\n"); | |
pthread_mutex_lock(&lock); | |
pthread_cond_wait(&cv, &lock); | |
printf("I've been unlocked.\n"); | |
pthread_mutex_unlock(&lock); | |
return NULL; | |
} | |
main() { | |
char cmd[1024]; | |
pthread_t *t; | |
printf("Type lock to run a thread that locks and waits.\n"); | |
printf("Type unlock to unlock the same thread.\n"); | |
while(fscanf(stdin, "%s", cmd) != EOF) { | |
if(strcmp(cmd, "lock") == 0) { | |
t = (pthread_t *) malloc(sizeof(pthread_t)); | |
pthread_create(t, NULL, thread, NULL); | |
} else if(strcmp(cmd, "unlock") == 0) { | |
pthread_cond_signal(&cv); | |
} | |
} | |
} |
I agree with @farrellit, you should wrap pthread_cond_wait(...)
in a while (!condition) { .. }
block and before signaling set the condition to true. Since "Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur." (see https://linux.die.net/man/3/pthread_cond_wait). So you need to check the condition again, also if the signal happens before the wait the thread will not finish.
Thank you so much.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Definitely, @brewmanz. I'd be surprised, especially with what you're showing, if this code worked.
I prefer this (scroll down)
http://man7.org/linux/man-pages/man3/pthread_cond_destroy.3p.html