From a1c9895543b6aa3deb6e42e7be83121b28f298ce Mon Sep 17 00:00:00 2001 From: Chris Dickens Date: Tue, 28 Apr 2015 14:56:00 -0700 Subject: examples: Address issues reported by Markus Elfring * Use sig_atomic_t as data type for variable do_exit * Use async-safe function within signal handler Closes #34 Signed-off-by: Chris Dickens --- examples/dpfp_threaded.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) (limited to 'examples') diff --git a/examples/dpfp_threaded.c b/examples/dpfp_threaded.c index 771e2ec..a7502a4 100644 --- a/examples/dpfp_threaded.c +++ b/examples/dpfp_threaded.c @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -64,16 +65,15 @@ static unsigned char irqbuf[INTR_LENGTH]; static struct libusb_transfer *img_transfer = NULL; static struct libusb_transfer *irq_transfer = NULL; static int img_idx = 0; -static int do_exit = 0; +static volatile sig_atomic_t do_exit = 0; static pthread_t poll_thread; -static pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER; -static pthread_mutex_t exit_cond_lock = PTHREAD_MUTEX_INITIALIZER; +static sem_t exit_sem; -static void request_exit(int code) +static void request_exit(sig_atomic_t code) { do_exit = code; - pthread_cond_signal(&exit_cond); + sem_post(&exit_sem); } static void *poll_thread_main(void *arg) @@ -446,9 +446,16 @@ int main(void) struct sigaction sigact; int r = 1; + r = sem_init(&exit_sem, 0, 0); + if (r) { + fprintf(stderr, "failed to initialise semaphore error %d", errno); + exit(1); + } + r = libusb_init(NULL); if (r < 0) { fprintf(stderr, "failed to initialise libusb\n"); + sem_destroy(&exit_sem); exit(1); } @@ -500,11 +507,8 @@ int main(void) goto out_deinit; } - while (!do_exit) { - pthread_mutex_lock(&exit_cond_lock); - pthread_cond_wait(&exit_cond, &exit_cond_lock); - pthread_mutex_unlock(&exit_cond_lock); - } + while (!do_exit) + sem_wait(&exit_sem); printf("shutting down...\n"); pthread_join(poll_thread, NULL); @@ -540,5 +544,6 @@ out_release: out: libusb_close(devh); libusb_exit(NULL); + sem_destroy(&exit_sem); return r >= 0 ? r : -r; } -- cgit v1.2.1