From dc89fc4ce2bdbc69657913c0514c307fe51b9118 Mon Sep 17 00:00:00 2001 From: PowerUser64 Date: Tue, 19 Nov 2024 15:08:22 -0800 Subject: [PATCH] mutex(fix): prevent race condition (part 2) In addition to the previous commit, this commit makes threads need to wait for the thread manager to say it took the mutex from them before they can ask for it again. --- main.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index ca4be50..4ff5749 100644 --- a/main.cpp +++ b/main.cpp @@ -55,10 +55,13 @@ void *thread_task_increment(const struct thread_data &thread) { // mutex { - // tell the thread manager we want the mutex + // wait for permission to ask for the mutex + while (!*thread.manager_took_mutex) + ; + // say we want the mutex (*thread.wants_mutex) = true; // block until we have the mutex - while (!*thread.has_mutex && *thread.manager_took_mutex) + while (!*thread.has_mutex) ; // enter the mutex