Skip to content

Instantly share code, notes, and snippets.

@ikonst
Last active August 29, 2015 14:25
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 ikonst/e7fdaddcc7973f44e7a3 to your computer and use it in GitHub Desktop.
Save ikonst/e7fdaddcc7973f44e7a3 to your computer and use it in GitHub Desktop.
Cancelable worker thread
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/errno.h>
struct thread_data {
pthread_cond_t cond;
int finished;
};
void get_relative_timespec(struct timespec *ts, int delay_sec)
{
struct timeval now;
gettimeofday(&now, NULL);
ts->tv_sec = now.tv_sec + delay_sec;
ts->tv_nsec = now.tv_usec * 1000;
}
void * threadfunc(void *arg) {
struct thread_data *data = (thread_data *) arg;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
do {
pthread_mutex_lock(&mutex);
// Perform "cancellable sleep"
struct timespec ts;
get_relative_timespec(&ts, 1);
if (pthread_cond_timedwait(&data->cond, &mutex, &ts) == ETIMEDOUT) {
printf("Doing work\n");
} else {
printf("Cancelled or spurious wakeup\n");
}
pthread_mutex_unlock(&mutex);
} while (!data->finished);
return NULL;
}
int main() {
pthread_t thread;
struct thread_data * data = (thread_data *) malloc(sizeof(thread_data));
data->cond = PTHREAD_COND_INITIALIZER;
data->finished = 0;
pthread_create(&thread, nullptr, threadfunc, data);
sleep(5);
printf("Ending worker thread\n");
data->finished = 1;
pthread_cond_signal(&data->cond);
pthread_join(thread, NULL);
free(data);
printf("Ended worker thread\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment