1 #ifndef mozilla_StaticMutex_h
2 #define mozilla_StaticMutex_h
4 #include "mozilla/Atomics.h"
5 #include "mozilla/Mutex.h"
10 * StaticMutex is a Mutex that can (and in fact, must) be used as a
11 * global/static variable.
13 * The main reason to use StaticMutex as opposed to
14 * StaticAutoPtr<OffTheBooksMutex> is that we instantiate the StaticMutex in a
15 * thread-safe manner the first time it's used.
17 * The same caveats that apply to StaticAutoPtr apply to StaticMutex. In
18 * particular, do not use StaticMutex as a stack variable or a class instance
19 * variable, because this class relies on the fact that global variablies are
20 * initialized to 0 in order to initialize mMutex. It is only safe to use
21 * StaticMutex as a global or static variable.
26 // In debug builds, check that mMutex is initialized for us as we expect by
27 // the compiler. In non-debug builds, don't declare a constructor so that
28 // the compiler can see that the constructor is trivial.
46 void AssertCurrentThreadOwns()
49 Mutex()->AssertCurrentThreadOwns();
54 OffTheBooksMutex
* Mutex()
60 OffTheBooksMutex
* mutex
= new OffTheBooksMutex("StaticMutex");
61 if (!mMutex
.compareExchange(nullptr, mutex
)) {
68 Atomic
<OffTheBooksMutex
*> mMutex
;
71 // Disallow copy constructor, but only in debug mode. We only define
72 // a default constructor in debug mode (see above); if we declared
73 // this constructor always, the compiler wouldn't generate a trivial
74 // default constructor for us in non-debug mode.
76 StaticMutex(StaticMutex
& aOther
);
79 // Disallow these operators.
80 StaticMutex
& operator=(StaticMutex
* aRhs
);
81 static void* operator new(size_t) CPP_THROW_NEW
;
82 static void operator delete(void*);
85 typedef BaseAutoLock
<StaticMutex
> StaticMutexAutoLock
;
86 typedef BaseAutoUnlock
<StaticMutex
> StaticMutexAutoUnlock
;
88 } // namespace mozilla