Last active
August 29, 2015 14:25
-
-
Save ikonst/e7fdaddcc7973f44e7a3 to your computer and use it in GitHub Desktop.
Cancelable worker thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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