From cc42c3a8ea0022b8777ed95c1f73b2a5845c5587 Mon Sep 17 00:00:00 2001 From: Michele Calgaro Date: Sat, 22 Mar 2025 17:47:07 +0900 Subject: Fix usage of condition variable in TQThread which could lead to a thread being run multiple times in parallel. Although highly unlikely, the following situation was possible: - a thread is restarted while still running. The call to the second 'start()' blocks because the thread is still running - the OS decides to randomly wake up the thread that called 'start()' - a second thread is started and runs in parallel to the first thread, with obvious undefined behavior Signed-off-by: Michele Calgaro (cherry picked from commit 3143d2d40ab5af1053596cd9b46c7034f22c4624) --- src/kernel/qthread_unix.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src/kernel/qthread_unix.cpp') diff --git a/src/kernel/qthread_unix.cpp b/src/kernel/qthread_unix.cpp index b68b5cd7a..723ca8bcf 100644 --- a/src/kernel/qthread_unix.cpp +++ b/src/kernel/qthread_unix.cpp @@ -107,7 +107,7 @@ void TQThreadInstance::init(unsigned int stackSize) orphan = FALSE; disableThreadPostedEvents = FALSE; - pthread_cond_init(&thread_done, NULL); + pthread_cond_init(&thread_done, nullptr); thread_id = 0; eventLoop = 0; @@ -326,9 +326,11 @@ void TQThread::usleep( unsigned long usecs ) void TQThread::start(Priority priority) { TQMutexLocker locker( d->mutex() ); + while ( d->running ) + { + pthread_cond_wait(&d->thread_done, &locker.mutex()->d->handle); + } - if ( d->running ) - pthread_cond_wait(&d->thread_done, &locker.mutex()->d->handle); d->running = TRUE; d->finished = FALSE; -- cgit v1.2.3