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().
This commit is contained in:
Andreas Kling 2021-07-05 22:56:54 +02:00
parent a6f0861c7b
commit c40780d404
Notes: sideshowbarker 2024-07-18 10:20:48 +09:00

View file

@ -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
*/
@ -7,14 +7,8 @@
#pragma once
#include <AK/Assertions.h>
#include <AK/Atomic.h>
#include <AK/Types.h>
#ifdef __serenity__
# include <unistd.h>
#else
# include <pthread.h>
#endif
#include <pthread.h>
namespace Threading {
@ -27,23 +21,7 @@ public:
void unlock();
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 {
@ -63,31 +41,12 @@ private:
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()
{
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>