Skip to content

Instantly share code, notes, and snippets.

@alexklibisz
Last active November 7, 2023 12:15
Show Gist options
  • Save alexklibisz/7cffdfe90c97986f8393 to your computer and use it in GitHub Desktop.
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.
#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);
}
}
}
@vianpl
Copy link

vianpl commented Aug 23, 2016

No need to initialise cv and lock?

@brewmanz
Copy link

I'd be inclined to initialise cv & lock
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
BTW this is a dump of pthread_cond_t internals, without and then with the initialiser:
L=20182272,F=0,T=140733535085552,Wa=140733535084496,Wo=4252151,M=0x133f500,N=341697520,B=32767
L=0,F=0,T=0,Wa=0,Wo=0,M=0,N=0,B=0

@farrellit
Copy link

farrellit commented Dec 12, 2017

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

@Manewing
Copy link

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.

@trilecao90
Copy link

Thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment