Skip to content

Instantly share code, notes, and snippets.

@a3f
Last active July 6, 2016 04:44
Show Gist options
  • Select an option

  • Save a3f/b4ac6b8b4d8c93ae65720cbb291408b2 to your computer and use it in GitHub Desktop.

Select an option

Save a3f/b4ac6b8b4d8c93ae65720cbb291408b2 to your computer and use it in GitHub Desktop.
Condition variable spurious wakeup example
#include <signal.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/param.h>
#ifdef BSD
#define INTERRUPT_CVAR SIGINFO
#else
#define INTERRUPT_CVAR SIGUSR1
#endif
volatile sig_atomic_t var = 0;
void sigint(int signo) {
if (signo == SIGINT)
return;
var = 1;
}
int main(void) {
pthread_cond_t cvar = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
signal(SIGINT, sigint);
signal(INTERRUPT_CVAR, sigint);
while (var == 0) {
puts("Waiting");
pthread_cond_wait(&cvar, &lock);
if (var == 0) {
puts("Spurious Wakeup");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment