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 mozilla_StaticMutex_h
8 #define mozilla_StaticMutex_h
10 #include "mozilla/Atomics.h"
11 #include "mozilla/Mutex.h"
16 * StaticMutex is a Mutex that can (and in fact, must) be used as a
17 * global/static variable.
19 * The main reason to use StaticMutex as opposed to
20 * StaticAutoPtr<OffTheBooksMutex> is that we instantiate the StaticMutex in a
21 * thread-safe manner the first time it's used.
23 * The same caveats that apply to StaticAutoPtr apply to StaticMutex. In
24 * particular, do not use StaticMutex as a stack variable or a class instance
25 * variable, because this class relies on the fact that global variablies are
26 * initialized to 0 in order to initialize mMutex. It is only safe to use
27 * StaticMutex as a global or static variable.
29 class MOZ_ONLY_USED_TO_AVOID_STATIC_CONSTRUCTORS
MOZ_CAPABILITY("mutex")
32 // In debug builds, check that mMutex is initialized for us as we expect by
33 // the compiler. In non-debug builds, don't declare a constructor so that
34 // the compiler can see that the constructor is trivial.
36 StaticMutex() { MOZ_ASSERT(!mMutex
); }
39 void Lock() MOZ_CAPABILITY_ACQUIRE() { Mutex()->Lock(); }
41 [[nodiscard
]] bool TryLock() MOZ_TRY_ACQUIRE(true) {
42 return Mutex()->TryLock();
45 void Unlock() MOZ_CAPABILITY_RELEASE() { Mutex()->Unlock(); }
47 void AssertCurrentThreadOwns() MOZ_ASSERT_CAPABILITY(this) {
49 Mutex()->AssertCurrentThreadOwns();
54 OffTheBooksMutex
* Mutex() {
59 OffTheBooksMutex
* mutex
= new OffTheBooksMutex("StaticMutex");
60 if (!mMutex
.compareExchange(nullptr, mutex
)) {
67 Atomic
<OffTheBooksMutex
*, SequentiallyConsistent
> mMutex
;
69 // Disallow copy constructor, but only in debug mode. We only define
70 // a default constructor in debug mode (see above); if we declared
71 // this constructor always, the compiler wouldn't generate a trivial
72 // default constructor for us in non-debug mode.
74 StaticMutex(StaticMutex
& aOther
);
77 // Disallow these operators.
78 StaticMutex
& operator=(StaticMutex
* aRhs
);
79 static void* operator new(size_t) noexcept(true);
80 static void operator delete(void*);
83 typedef detail::BaseAutoLock
<StaticMutex
&> StaticMutexAutoLock
;
84 typedef detail::BaseAutoUnlock
<StaticMutex
&> StaticMutexAutoUnlock
;
86 } // namespace mozilla