1 // Copyright 2018 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "src/execution/thread-id.h" 6 #include "src/base/lazy-instance.h" 7 #include "src/base/platform/platform.h" 8 9 namespace v8 { 10 namespace internal { 11 12 namespace { 13 DEFINE_LAZY_LEAKY_OBJECT_GETTER(base::Thread::LocalStorageKey,GetThreadIdKey,base::Thread::CreateThreadLocalKey ())14DEFINE_LAZY_LEAKY_OBJECT_GETTER(base::Thread::LocalStorageKey, GetThreadIdKey, 15 base::Thread::CreateThreadLocalKey()) 16 17 std::atomic<int> next_thread_id{1}; 18 19 } // namespace 20 21 // static TryGetCurrent()22ThreadId ThreadId::TryGetCurrent() { 23 int thread_id = base::Thread::GetThreadLocalInt(*GetThreadIdKey()); 24 return thread_id == 0 ? Invalid() : ThreadId(thread_id); 25 } 26 27 // static GetCurrentThreadId()28int ThreadId::GetCurrentThreadId() { 29 auto key = *GetThreadIdKey(); 30 int thread_id = base::Thread::GetThreadLocalInt(key); 31 if (thread_id == 0) { 32 thread_id = next_thread_id.fetch_add(1); 33 CHECK_LE(1, thread_id); 34 base::Thread::SetThreadLocalInt(key, thread_id); 35 } 36 return thread_id; 37 } 38 39 } // namespace internal 40 } // namespace v8 41