SharedScriptDataTableHolder.h (2753B)
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 vm_SharedScriptDataTableHolder_h 8 #define vm_SharedScriptDataTableHolder_h 9 10 #include "mozilla/Assertions.h" // MOZ_ASSERT 11 #include "mozilla/Maybe.h" // mozilla::Maybe 12 13 #include "threading/Mutex.h" // js::Mutex 14 #include "vm/SharedStencil.h" // js::SharedImmutableScriptDataTable 15 16 namespace js { 17 18 class AutoLockGlobalScriptData { 19 static js::Mutex mutex_; 20 21 public: 22 AutoLockGlobalScriptData(); 23 ~AutoLockGlobalScriptData(); 24 }; 25 26 // A class to provide an access to SharedImmutableScriptDataTable, 27 // with or without a mutex lock. 28 // 29 // js::globalSharedScriptDataTableHolder singleton can be used by any thread, 30 // and it needs a mutex lock. 31 // 32 // AutoLockGlobalScriptData lock; 33 // auto& table = js::globalSharedScriptDataTableHolder::get(lock); 34 // 35 // Private SharedScriptDataTableHolder instance can be created for thread-local 36 // storage, and it can be configured not to require a mutex lock. 37 // 38 // SharedScriptDataTableHolder holder( 39 // SharedScriptDataTableHolder::NeedsLock::No); 40 // ... 41 // auto& table = holder.getWithoutLock(); 42 // 43 // getMaybeLocked method can be used for both type of instances. 44 // 45 // Maybe<AutoLockGlobalScriptData> lock; 46 // auto& table = holder.getMaybeLocked(lock); 47 // 48 // Private instance is supposed to be held by the each JSRuntime, including 49 // both main thread runtime and worker thread runtime, and used in for 50 // non-helper-thread compilation. 51 // 52 // js::globalSharedScriptDataTableHolder singleton is supposed to be used by 53 // all helper-thread compilation. 54 class SharedScriptDataTableHolder { 55 bool needsLock_ = true; 56 js::SharedImmutableScriptDataTable scriptDataTable_; 57 58 public: 59 enum class NeedsLock { No, Yes }; 60 61 explicit SharedScriptDataTableHolder(NeedsLock needsLock = NeedsLock::Yes) 62 : needsLock_(needsLock == NeedsLock::Yes) {} 63 64 js::SharedImmutableScriptDataTable& get( 65 const js::AutoLockGlobalScriptData& lock) { 66 MOZ_ASSERT(needsLock_); 67 return scriptDataTable_; 68 } 69 70 js::SharedImmutableScriptDataTable& getWithoutLock() { 71 MOZ_ASSERT(!needsLock_); 72 return scriptDataTable_; 73 } 74 75 js::SharedImmutableScriptDataTable& getMaybeLocked( 76 mozilla::Maybe<js::AutoLockGlobalScriptData>& lock) { 77 if (needsLock_) { 78 lock.emplace(); 79 } 80 return scriptDataTable_; 81 } 82 }; 83 84 extern SharedScriptDataTableHolder globalSharedScriptDataTableHolder; 85 86 } /* namespace js */ 87 88 #endif /* vm_SharedScriptDataTableHolder_h */