Bug 1942784 - Add <input type=file multiple> test as geckoview-junit. r=geckoview...
[gecko.git] / xpcom / base / StaticMutex.h
blobd73ea5b2d611be386f576d87d911be28d8a9fd9a
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 [[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) {
48 #ifdef DEBUG
49 Mutex()->AssertCurrentThreadOwns();
50 #endif
53 private:
54 OffTheBooksMutex* Mutex() {
55 if (mMutex) {
56 return mMutex;
59 OffTheBooksMutex* mutex = new OffTheBooksMutex("StaticMutex");
60 if (!mMutex.compareExchange(nullptr, mutex)) {
61 delete mutex;
64 return mMutex;
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.
73 #ifdef DEBUG
74 StaticMutex(StaticMutex& aOther);
75 #endif
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
88 #endif