thread-id.cc 1.05 KB
Newer Older
1 2 3 4
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/execution/thread-id.h"
6 7 8 9 10 11 12 13
#include "src/base/lazy-instance.h"
#include "src/base/platform/platform.h"

namespace v8 {
namespace internal {

namespace {

14
DEFINE_LAZY_LEAKY_OBJECT_GETTER(base::Thread::LocalStorageKey, GetThreadIdKey,
15
                                base::Thread::CreateThreadLocalKey())
16

17 18
std::atomic<int> next_thread_id{1};

19 20 21 22
}  // namespace

// static
ThreadId ThreadId::TryGetCurrent() {
23
  int thread_id = base::Thread::GetThreadLocalInt(*GetThreadIdKey());
24 25 26 27 28
  return thread_id == 0 ? Invalid() : ThreadId(thread_id);
}

// static
int ThreadId::GetCurrentThreadId() {
29 30
  auto key = *GetThreadIdKey();
  int thread_id = base::Thread::GetThreadLocalInt(key);
31
  if (thread_id == 0) {
32 33 34
    thread_id = next_thread_id.fetch_add(1);
    CHECK_LE(1, thread_id);
    base::Thread::SetThreadLocalInt(key, thread_id);
35 36 37 38 39 40
  }
  return thread_id;
}

}  // namespace internal
}  // namespace v8