From c0eb2e5193d69534ec3dff001a8e555c71097e82 Mon Sep 17 00:00:00 2001 From: John Sully Date: Sat, 16 Feb 2019 14:25:14 -0500 Subject: [PATCH] Fix recursive fastlock... --- src/fastlock.cpp | 28 ++++++++++++++++++++-------- src/fastlock.h | 4 ++-- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/fastlock.cpp b/src/fastlock.cpp index 08d6368f0..9c4e4f1c7 100644 --- a/src/fastlock.cpp +++ b/src/fastlock.cpp @@ -1,7 +1,18 @@ #include "fastlock.h" #include +#include +#include +#include -thread_local int tls_pid = -1; +static_assert(sizeof(pid_t) <= sizeof(fastlock::m_pidOwner), "fastlock::m_pidOwner not large enough"); + +static pid_t gettid() +{ + static thread_local int pidCache = -1; + if (pidCache == -1) + pidCache = syscall(SYS_gettid); + return pidCache; +} extern "C" void fastlock_init(struct fastlock *lock) { @@ -11,16 +22,18 @@ extern "C" void fastlock_init(struct fastlock *lock) extern "C" void fastlock_lock(struct fastlock *lock) { + if (lock->m_pidOwner == gettid()) + { + ++lock->m_depth; + return; + } + while (!__sync_bool_compare_and_swap(&lock->m_lock, 0, 1)) { - if (lock->m_pidOwner == getpid()) - { - ++lock->m_depth; - return; - } + sched_yield(); } lock->m_depth = 1; - lock->m_pidOwner = getpid(); + lock->m_pidOwner = gettid(); } extern "C" void fastlock_unlock(struct fastlock *lock) @@ -29,7 +42,6 @@ extern "C" void fastlock_unlock(struct fastlock *lock) if (lock->m_depth == 0) { lock->m_pidOwner = -1; - asm volatile ("": : :"memory"); __sync_bool_compare_and_swap(&lock->m_lock, 1, 0); } } diff --git a/src/fastlock.h b/src/fastlock.h index e6c496ab2..b5ddc597f 100644 --- a/src/fastlock.h +++ b/src/fastlock.h @@ -19,8 +19,8 @@ void fastlock_free(struct fastlock *lock); struct fastlock { volatile int m_lock; - int m_pidOwner; - int m_depth; + volatile int m_pidOwner; + volatile int m_depth; #ifdef __cplusplus fastlock()