Skip to content

Instantly share code, notes, and snippets.

@bnham
Last active August 22, 2017 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnham/f2ca3430a7c4f6f714a918b62702125e to your computer and use it in GitHub Desktop.
Save bnham/f2ca3430a7c4f6f714a918b62702125e to your computer and use it in GitHub Desktop.
/*
In one terminal:
$ ./cond
pid is 20274
Running busy loop thread
Waiting on condition!
pthread_cond_wait returned 0
Got past condition, handled signal: 1
In another terminal:
$ kill -USR1 20274
*/
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static int handledSignal = 0;
static pthread_t busyLoopThread;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void *busyLoop(void *ctx) {
static pthread_mutex_t sleepLock = PTHREAD_MUTEX_INITIALIZER;
printf("Running busy loop thread\n");
// deadlock myself
pthread_mutex_lock(&sleepLock);
pthread_mutex_lock(&sleepLock);
return NULL;
}
static void handleSignal(int signal) {
handledSignal = 1;
}
int main() {
printf("pid is %d\n", getpid());
struct sigaction sa = {};
sa.sa_handler = &handleSignal;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGUSR1, &sa, NULL) == -1) {
perror("sigaction");
}
// copied from StartWebThread, unlikely to be relevant
pthread_attr_t tattr;
pthread_attr_init(&tattr);
pthread_attr_setscope(&tattr, PTHREAD_SCOPE_SYSTEM);
pthread_attr_setstacksize(&tattr, 200 * 4096);
pthread_create(&busyLoopThread, &tattr, busyLoop, NULL);
pthread_attr_destroy(&tattr);
pthread_mutex_lock(&lock);
printf("Waiting on condition!\n");
int result = pthread_cond_wait(&cond, &lock);
if (result != 0) {
perror("pthread_cond_wait");
} else {
printf("pthread_cond_wait returned 0\n");
}
pthread_mutex_unlock(&lock);
printf("Got past condition, handled signal: %d\n", handledSignal);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment