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 threading_Thread_h 8 #define threading_Thread_h 9 10 #include "mozilla/Atomics.h" 11 #include "mozilla/Attributes.h" 12 #include "mozilla/TimeStamp.h" 13 #include "mozilla/Tuple.h" 14 15 #include <stdint.h> 16 #include <type_traits> 17 #include <utility> 18 19 #include "js/Initialization.h" 20 #include "js/Utility.h" 21 #include "threading/LockGuard.h" 22 #include "threading/Mutex.h" 23 #include "threading/ThreadId.h" 24 #include "vm/MutexIDs.h" 25 26 #ifdef XP_WIN 27 # define THREAD_RETURN_TYPE unsigned int 28 # define THREAD_CALL_API __stdcall 29 #else 30 # define THREAD_RETURN_TYPE void* 31 # define THREAD_CALL_API 32 #endif 33 34 namespace js { 35 namespace detail { 36 template <typename F, typename... Args> 37 class ThreadTrampoline; 38 } // namespace detail 39 40 // Execute the given functor concurrent with the currently executing instruction 41 // stream and within the current address space. Use with care. 42 class Thread { 43 public: 44 // Provides optional parameters to a Thread. 45 class Options { 46 size_t stackSize_; 47 48 public: Options()49 Options() : stackSize_(0) {} 50 setStackSize(size_t sz)51 Options& setStackSize(size_t sz) { 52 stackSize_ = sz; 53 return *this; 54 } stackSize()55 size_t stackSize() const { return stackSize_; } 56 }; 57 58 // Create a Thread in an initially unjoinable state. A thread of execution can 59 // be created for this Thread by calling |init|. Some of the thread's 60 // properties may be controlled by passing options to this constructor. 61 template <typename O = Options, 62 // SFINAE to make sure we don't try and treat functors for the other 63 // constructor as an Options and vice versa. 64 typename NonConstO = std::remove_const_t<O>, 65 typename DerefO = std::remove_reference_t<NonConstO>, 66 typename = std::enable_if_t<std::is_same_v<DerefO, Options>>> 67 explicit Thread(O&& options = Options()) id_(ThreadId ())68 : id_(ThreadId()), options_(std::forward<O>(options)) { 69 MOZ_ASSERT(isInitialized()); 70 } 71 72 // Start a thread of execution at functor |f| with parameters |args|. This 73 // method will return false if thread creation fails. This Thread must not 74 // already have been created. Note that the arguments must be either POD or 75 // rvalue references (std::move). Attempting to pass a reference will 76 // result in the value being copied, which may not be the intended behavior. 77 // See the comment below on ThreadTrampoline::args for an explanation. 78 template <typename F, typename... Args> init(F && f,Args &&...args)79 MOZ_MUST_USE bool init(F&& f, Args&&... args) { 80 MOZ_RELEASE_ASSERT(id_ == ThreadId()); 81 using Trampoline = detail::ThreadTrampoline<F, Args...>; 82 auto trampoline = 83 js_new<Trampoline>(std::forward<F>(f), std::forward<Args>(args)...); 84 if (!trampoline) { 85 return false; 86 } 87 88 // We hold this lock while create() sets the thread id. 89 LockGuard<Mutex> lock(trampoline->createMutex); 90 return create(Trampoline::Start, trampoline); 91 } 92 93 // The thread must be joined or detached before destruction. 94 ~Thread(); 95 96 // Move the thread into the detached state without blocking. In the detatched 97 // state, the thread continues to run until it exits, but cannot be joined. 98 // After this method returns, this Thread no longer represents a thread of 99 // execution. When the thread exits, its resources will be cleaned up by the 100 // system. At process exit, if the thread is still running, the thread's TLS 101 // storage will be destructed, but the thread stack will *not* be unrolled. 102 void detach(); 103 104 // Block the current thread until this Thread returns from the functor it was 105 // created with. The thread's resources will be cleaned up before this 106 // function returns. After this method returns, this Thread no longer 107 // represents a thread of execution. 108 void join(); 109 110 // Return true if this thread has not yet been joined or detached. If this 111 // method returns false, this Thread does not have an associated thread of 112 // execution, for example, if it has been previously moved or joined. 113 bool joinable(); 114 115 // Returns the id of this thread if this represents a thread of execution or 116 // the default constructed Id() if not. The thread ID is guaranteed to 117 // uniquely identify a thread and can be compared with the == operator. 118 ThreadId get_id(); 119 120 // Allow threads to be moved so that they can be stored in containers. 121 Thread(Thread&& aOther); 122 Thread& operator=(Thread&& aOther); 123 124 private: 125 // Disallow copy as that's not sensible for unique resources. 126 Thread(const Thread&) = delete; 127 void operator=(const Thread&) = delete; 128 129 // Provide a process global ID to each thread. 130 ThreadId id_; 131 132 // Overridable thread creation options. 133 Options options_; 134 135 // Dispatch to per-platform implementation of thread creation. 136 MOZ_MUST_USE bool create(THREAD_RETURN_TYPE(THREAD_CALL_API* aMain)(void*), 137 void* aArg); 138 139 // An internal version of JS_IsInitialized() that returns whether SpiderMonkey 140 // is currently initialized or is in the process of being initialized. isInitialized()141 static inline bool isInitialized() { 142 using namespace JS::detail; 143 return libraryInitState == InitState::Initializing || 144 libraryInitState == InitState::Running; 145 } 146 }; 147 148 namespace ThisThread { 149 150 // Set the current thread name. Note that setting the thread name may not be 151 // available on all platforms; on these platforms setName() will simply do 152 // nothing. 153 void SetName(const char* name); 154 155 // Get the current thread name. As with SetName, not available on all 156 // platforms. On these platforms getName() will give back an empty string (by 157 // storing NUL in nameBuffer[0]). 'len' is the bytes available to be written in 158 // 'nameBuffer', including the terminating NUL. 159 void GetName(char* nameBuffer, size_t len); 160 161 } // namespace ThisThread 162 163 namespace detail { 164 165 // Platform thread APIs allow passing a single void* argument to the target 166 // thread. This class is responsible for safely ferrying the arg pack and 167 // functor across that void* membrane and running it in the other thread. 168 template <typename F, typename... Args> 169 class ThreadTrampoline { 170 // The functor to call. 171 F f; 172 173 // A std::decay copy of the arguments, as specified by std::thread. Using an 174 // rvalue reference for the arguments to Thread and ThreadTrampoline gives us 175 // move semantics for large structures, allowing us to quickly and easily pass 176 // enormous amounts of data to a new thread. Unfortunately, there is a 177 // downside: rvalue references becomes lvalue references when used with POD 178 // types. This becomes dangerous when attempting to pass POD stored on the 179 // stack to the new thread; the rvalue reference will implicitly become an 180 // lvalue reference to the stack location. Thus, the value may not exist if 181 // the parent thread leaves the frame before the read happens in the new 182 // thread. To avoid this dangerous and highly non-obvious footgun, the 183 // standard requires a "decay" copy of the arguments at the cost of making it 184 // impossible to pass references between threads. 185 mozilla::Tuple<std::decay_t<Args>...> args; 186 187 // Protect the thread id during creation. 188 Mutex createMutex; 189 190 // Thread can access createMutex. 191 friend class js::Thread; 192 193 public: 194 // Note that this template instatiation duplicates and is identical to the 195 // class template instantiation. It is required for perfect forwarding of 196 // rvalue references, which is only enabled for calls to a function template, 197 // even if the class template arguments are correct. 198 template <typename G, typename... ArgsT> ThreadTrampoline(G && aG,ArgsT &&...aArgsT)199 explicit ThreadTrampoline(G&& aG, ArgsT&&... aArgsT) 200 : f(std::forward<F>(aG)), 201 args(std::forward<Args>(aArgsT)...), 202 createMutex(mutexid::ThreadId) {} 203 Start(void * aPack)204 static THREAD_RETURN_TYPE THREAD_CALL_API Start(void* aPack) { 205 auto* pack = static_cast<ThreadTrampoline<F, Args...>*>(aPack); 206 pack->callMain(std::index_sequence_for<Args...>{}); 207 js_delete(pack); 208 return 0; 209 } 210 211 template <size_t... Indices> callMain(std::index_sequence<Indices...>)212 void callMain(std::index_sequence<Indices...>) { 213 // Pretend createMutex is a semaphore and wait for a notification that the 214 // thread that spawned us is ready. 215 createMutex.lock(); 216 createMutex.unlock(); 217 f(mozilla::Get<Indices>(args)...); 218 } 219 }; 220 221 } // namespace detail 222 } // namespace js 223 224 #undef THREAD_RETURN_TYPE 225 226 #endif // threading_Thread_h 227