From cd8173bc13b7fa55b46d20b954cfe3fa114631e4 Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Wed, 5 May 2021 14:12:13 +1000 Subject: [PATCH] pthread: Fix possible deadlock when using pthread_join() and Debug log level Possible for a joined task to be deleted at the moment it is logging, meaning it might hold the stdout lock. In that case the lock isn't released and the next task to try and take it (i.e. call printf) will block indefinitely. --- components/pthread/pthread.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/components/pthread/pthread.c b/components/pthread/pthread.c index 77e8afd524..8b14c1fc80 100644 --- a/components/pthread/pthread.c +++ b/components/pthread/pthread.c @@ -360,7 +360,7 @@ int pthread_join(pthread_t thread, void **retval) if (pthread->state == PTHREAD_TASK_STATE_RUN) { pthread->join_task = xTaskGetCurrentTaskHandle(); wait = true; - } else { + } else { // thread has exited and task is already suspended, or about to be suspended child_task_retval = pthread->retval; pthread_delete(pthread); } @@ -451,10 +451,14 @@ void pthread_exit(void *value_ptr) pthread->state = PTHREAD_TASK_STATE_EXIT; } } - xSemaphoreGive(s_threads_mux); ESP_LOGD(TAG, "Task stk_wm = %d", uxTaskGetStackHighWaterMark(NULL)); + xSemaphoreGive(s_threads_mux); + // note: if this thread is joinable then after giving back s_threads_mux + // this task could be deleted at any time, so don't take another lock or + // do anything that might lock (such as printing to stdout) + if (detached) { vTaskDelete(NULL); } else {