Line data Source code
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/. */
6 :
7 : #ifndef threading_Mutex_h
8 : #define threading_Mutex_h
9 :
10 : #include "mozilla/Assertions.h"
11 : #include "mozilla/Move.h"
12 : #include "mozilla/PlatformMutex.h"
13 : #include "mozilla/ThreadLocal.h"
14 : #include "mozilla/Vector.h"
15 :
16 : namespace js {
17 :
18 : // A MutexId secifies the name and mutex order for a mutex.
19 : //
20 : // The mutex order defines the allowed order of mutex acqusition on a single
21 : // thread. Mutexes must be acquired in strictly increasing order. Mutexes with
22 : // the same order may not be held at the same time by that thread.
23 : struct MutexId
24 : {
25 : const char* name;
26 : uint32_t order;
27 : };
28 :
29 : #ifndef DEBUG
30 :
31 : class Mutex : public mozilla::detail::MutexImpl
32 : {
33 : public:
34 : static bool Init() { return true; }
35 : static void ShutDown() {}
36 :
37 : explicit Mutex(const MutexId& id) {}
38 :
39 : using MutexImpl::lock;
40 : using MutexImpl::unlock;
41 : };
42 :
43 : #else
44 :
45 : // In debug builds, js::Mutex is a wrapper over MutexImpl that checks correct
46 : // locking order is observed.
47 : //
48 : // The class maintains a per-thread stack of currently-held mutexes to enable it
49 : // to check this.
50 0 : class Mutex : public mozilla::detail::MutexImpl
51 : {
52 : public:
53 : static bool Init();
54 : static void ShutDown();
55 :
56 95 : explicit Mutex(const MutexId& id)
57 95 : : id_(id)
58 : {
59 95 : MOZ_ASSERT(id_.order != 0);
60 95 : }
61 :
62 : void lock();
63 : void unlock();
64 : bool ownedByCurrentThread() const;
65 :
66 : private:
67 : const MutexId id_;
68 :
69 : using MutexVector = mozilla::Vector<const Mutex*>;
70 : static MOZ_THREAD_LOCAL(MutexVector*) HeldMutexStack;
71 : static MutexVector& heldMutexStack();
72 : };
73 :
74 : #endif
75 :
76 : } // namespace js
77 :
78 : #endif // threading_Mutex_h
|