1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef threading_Mutex_h
8 #define threading_Mutex_h
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Maybe.h"
12 #include "mozilla/PlatformMutex.h"
13 #include "mozilla/ThreadLocal.h"
14 #include "mozilla/Vector.h"
18 #include "threading/ThreadId.h"
22 // A MutexId secifies the name and mutex order for a mutex.
24 // The mutex order defines the allowed order of mutex acqusition on a single
25 // thread. Mutexes must be acquired in strictly increasing order. Mutexes with
26 // the same order may not be held at the same time by that thread.
32 // The Mutex class below wraps mozilla::detail::MutexImpl, but we don't want to
33 // use public inheritance, and private inheritance is problematic because
34 // Mutex's friends can access the private parent class as if it was public
35 // inheritance. So use a data member, but for Mutex to access the data member
36 // we must override it and make Mutex a friend.
37 class MutexImpl
: public mozilla::detail::MutexImpl
{
39 MutexImpl() : mozilla::detail::MutexImpl() {}
44 // In debug builds, js::Mutex is a wrapper over MutexImpl that checks correct
45 // locking order is observed.
47 // The class maintains a per-thread stack of currently-held mutexes to enable it
55 Mutex
* prev_
= nullptr;
56 ThreadId owningThread_
;
58 static MOZ_THREAD_LOCAL(Mutex
*) HeldMutexStack
;
65 explicit Mutex(const MutexId
& id
) : id_(id
) { MOZ_ASSERT(id_
.order
!= 0); }
70 bool isOwnedByCurrentThread() const;
71 void assertOwnedByCurrentThread() const;
73 static bool Init() { return true; }
75 explicit Mutex(const MutexId
& id
) {}
77 void lock() { impl_
.lock(); }
78 bool tryLock() { return impl_
.tryLock(); }
79 void unlock() { impl_
.unlock(); }
80 void assertOwnedByCurrentThread() const {};
85 void preLockChecks() const;
86 void postLockChecks();
87 void preUnlockChecks();
90 friend class ConditionVariable
;
95 #endif // threading_Mutex_h