From 0629d9db616552b97e349402ef4ba504b9eef1be Mon Sep 17 00:00:00 2001 From: David Fries Date: Thu, 8 Nov 2012 22:26:17 -0600 Subject: [PATCH] set motion capture thread running in the main thread I identified this while debugging, the thread was created, but hadn't yet set its state to running before the main thread checked the running variable and started another thread for the same device. That resulted in a crash. Set running in the main thread, to avoid this race condition. --- motion.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/motion.c b/motion.c index 9b88b431..f655c729 100644 --- a/motion.c +++ b/motion.c @@ -1088,8 +1088,6 @@ static void *motion_loop(void *arg) */ unsigned long int time_last_frame = 1, time_current_frame; - cnt->running = 1; - if (motion_init(cnt) < 0) goto err; @@ -2595,11 +2593,22 @@ static void start_motion_thread(struct context *cnt, pthread_attr_t *thread_attr /* Give the thread WATCHDOG_TMO to start */ cnt->watchdog = WATCHDOG_TMO; + /* Flag it as running outside of the thread, otherwise if the main loop + * checked if it is was running before the thread set it to 1, it would + * start another thread for this device. */ + cnt->running = 1; + /* * Create the actual thread. Use 'motion_loop' as the thread * function. */ - pthread_create(&cnt->thread_id, thread_attr, &motion_loop, cnt); + if (pthread_create(&cnt->thread_id, thread_attr, &motion_loop, cnt)) { + /* thread create failed, undo running state */ + cnt->running = 0; + pthread_mutex_lock(&global_lock); + threads_running--; + pthread_mutex_unlock(&global_lock); + } } /**