Backed out changeset bd51857879db (bug 1862957) for causing WakeLock related failures...
[gecko.git] / xpcom / base / StaticMutex.h
blob08c0288486018bd84ebf99b4b6fc4eec3d0ae5aa
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"
13 namespace mozilla {
15 /**
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")
30 StaticMutex {
31 public:
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.
35 #ifdef DEBUG
36 StaticMutex() { MOZ_ASSERT(!mMutex); }
37 #endif
39 void Lock() MOZ_CAPABILITY_ACQUIRE() { Mutex()->Lock(); }
41 void Unlock() MOZ_CAPABILITY_RELEASE() { Mutex()->Unlock(); }
43 void AssertCurrentThreadOwns() MOZ_ASSERT_CAPABILITY(this) {
44 #ifdef DEBUG
45 Mutex()->AssertCurrentThreadOwns();
46 #endif
49 private:
50 OffTheBooksMutex* Mutex() {
51 if (mMutex) {
52 return mMutex;
55 OffTheBooksMutex* mutex = new OffTheBooksMutex("StaticMutex");
56 if (!mMutex.compareExchange(nullptr, mutex)) {
57 delete mutex;
60 return mMutex;
63 Atomic<OffTheBooksMutex*, SequentiallyConsistent> mMutex;
65 // Disallow copy constructor, but only in debug mode. We only define
66 // a default constructor in debug mode (see above); if we declared
67 // this constructor always, the compiler wouldn't generate a trivial
68 // default constructor for us in non-debug mode.
69 #ifdef DEBUG
70 StaticMutex(StaticMutex& aOther);
71 #endif
73 // Disallow these operators.
74 StaticMutex& operator=(StaticMutex* aRhs);
75 static void* operator new(size_t) noexcept(true);
76 static void operator delete(void*);
79 typedef detail::BaseAutoLock<StaticMutex&> StaticMutexAutoLock;
80 typedef detail::BaseAutoUnlock<StaticMutex&> StaticMutexAutoUnlock;
82 } // namespace mozilla
84 #endif