Pārlūkot izejas kodu

LibThreading: Reimplement Lock in terms of pthread_mutex_t

This class was previously a spinlock that would call sys$donate()
to donate its timeslice to whichever thread was holding the lock.

Now that pthread_mutex_t has a fast path, let's implement Lock on top
of that instead and get rid of the last remaining user of sys$donate().
Andreas Kling 4 gadi atpakaļ
vecāks
revīzija
c40780d404
1 mainītis faili ar 5 papildinājumiem un 46 dzēšanām
  1. 5 46
      Userland/Libraries/LibThreading/Lock.h

+ 5 - 46
Userland/Libraries/LibThreading/Lock.h

@@ -1,5 +1,5 @@
 /*
 /*
- * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
+ * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  *
  *
  * SPDX-License-Identifier: BSD-2-Clause
  * SPDX-License-Identifier: BSD-2-Clause
  */
  */
@@ -7,14 +7,8 @@
 #pragma once
 #pragma once
 
 
 #include <AK/Assertions.h>
 #include <AK/Assertions.h>
-#include <AK/Atomic.h>
 #include <AK/Types.h>
 #include <AK/Types.h>
-
-#ifdef __serenity__
-#    include <unistd.h>
-#else
-#    include <pthread.h>
-#endif
+#include <pthread.h>
 
 
 namespace Threading {
 namespace Threading {
 
 
@@ -27,23 +21,7 @@ public:
     void unlock();
     void unlock();
 
 
 private:
 private:
-#ifdef __serenity__
-    using ThreadID = int;
-
-    ALWAYS_INLINE static ThreadID self()
-    {
-        return gettid();
-    }
-#else
-    using ThreadID = pthread_t;
-
-    ALWAYS_INLINE static ThreadID self()
-    {
-        return pthread_self();
-    }
-#endif
-    Atomic<ThreadID> m_holder { 0 };
-    u32 m_level { 0 };
+    pthread_mutex_t m_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
 };
 };
 
 
 class Locker {
 class Locker {
@@ -63,31 +41,12 @@ private:
 
 
 ALWAYS_INLINE void Lock::lock()
 ALWAYS_INLINE void Lock::lock()
 {
 {
-    ThreadID tid = self();
-    if (m_holder == tid) {
-        ++m_level;
-        return;
-    }
-    for (;;) {
-        ThreadID expected = 0;
-        if (m_holder.compare_exchange_strong(expected, tid, AK::memory_order_acq_rel)) {
-            m_level = 1;
-            return;
-        }
-#ifdef __serenity__
-        donate(expected);
-#endif
-    }
+    pthread_mutex_lock(&m_mutex);
 }
 }
 
 
 inline void Lock::unlock()
 inline void Lock::unlock()
 {
 {
-    VERIFY(m_holder == self());
-    VERIFY(m_level);
-    if (m_level == 1)
-        m_holder.store(0, AK::memory_order_release);
-    else
-        --m_level;
+    pthread_mutex_unlock(&m_mutex);
 }
 }
 
 
 template<typename T>
 template<typename T>