Skip to content

Instantly share code, notes, and snippets.

@aprell
Created March 22, 2013 15:09
Show Gist options
  • Select an option

  • Save aprell/5221996 to your computer and use it in GitHub Desktop.

Select an option

Save aprell/5221996 to your computer and use it in GitHub Desktop.
Sending signals to threads with pthread_kill
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>
#include <signal.h>
#include <errno.h>
static pthread_t threads[2];
static int IDs[2] = { 1, 2 };
static int data, running, done;
static void signal_handler(int sig)
{
data++;
}
static void *thread_func_2(void *args)
{
int ID = *(int *)args;
running = 1;
while (!*(volatile int *)&done) {
sleep(0);
}
printf("Thread %d: data = %d\n", ID, data);
return NULL;
}
static void *thread_func_1(void *args)
{
int i;
// Make sure the other thread is up and running
// pthread_kill may catch invalid thread IDs and return ESRCH,
// but may just as well segfault
// See http://udrepper.livejournal.com/16844.html
while (!*(volatile int *)&running) ;
#define N 100
// Send N signals
for (i = 0; i < N; i++) {
// Do something
int fib = 0, f2 = 0, f1 = 1, j;
for (j = 2; j <= 30; j++) {
fib = f1 + f2;
f2 = f1;
f1 = fib;
}
assert(pthread_kill(threads[1], SIGUSR1) == 0);
}
done = 1;
return NULL;
}
int main(void)
{
struct sigaction action;
// Register signal handler
action.sa_handler = signal_handler;
action.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &action, NULL);
pthread_create(&threads[0], NULL, thread_func_1, &IDs[0]);
pthread_create(&threads[1], NULL, thread_func_2, &IDs[1]);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment