Skip to content

Instantly share code, notes, and snippets.

@dram
Created May 31, 2013 10:31
Show Gist options
  • Select an option

  • Save dram/5684164 to your computer and use it in GitHub Desktop.

Select an option

Save dram/5684164 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
static void debug(const char *msg) {
time_t t = time(NULL);
fprintf(stderr, "%s%s\n\n", ctime(&t), msg);
}
void *thread(void *arg)
{
int i;
debug("Blocking cancel request.");
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
for (i = 0; i < 10; ++i) {
debug("Do something...");
sleep(1);
}
debug("Unblocking cancel request.");
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
debug("Will not reach here...");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t tid;
if (pthread_create(&tid, NULL, thread, NULL) != 0) {
perror("pthread_create");
exit(1);
}
sleep(5);
debug("Sending cancel request...");
pthread_cancel(tid);
pthread_join(tid, NULL);
debug("Thread canceled.");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment