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#ifndef V8_THREAD_ID_H_
6#define V8_THREAD_ID_H_
7
8#include "src/base/macros.h"
9
10namespace v8 {
11namespace internal {
12
13// Platform-independent, reliable thread identifier.
14class ThreadId {
15 public:
16 // Creates an invalid ThreadId.
17 constexpr ThreadId() noexcept : ThreadId(kInvalidId) {}
18
19 bool operator==(const ThreadId& other) const { return id_ == other.id_; }
20 bool operator!=(const ThreadId& other) const { return id_ != other.id_; }
21
22 // Checks whether this ThreadId refers to any thread.
23 bool IsValid() const { return id_ != kInvalidId; }
24
25 // Converts ThreadId to an integer representation.
26 constexpr int ToInteger() const { return id_; }
27
28 // Returns ThreadId for current thread if it exists or invalid id.
29 static ThreadId TryGetCurrent();
30
31 // Returns ThreadId for current thread.
32 static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }
33
34 // Returns invalid ThreadId (guaranteed not to be equal to any thread).
35 static constexpr ThreadId Invalid() { return ThreadId(kInvalidId); }
36
37 // Converts ThreadId to an integer representation
38 // (required for public API: V8::V8::TerminateExecution).
39 static constexpr ThreadId FromInteger(int id) { return ThreadId(id); }
40
41 private:
42 static constexpr int kInvalidId = -1;
43
44 explicit constexpr ThreadId(int id) noexcept : id_(id) {}
45
46 V8_EXPORT_PRIVATE static int GetCurrentThreadId();
47
48 int id_;
49};
50
51} // namespace internal
52} // namespace v8
53
54#endif // V8_THREAD_ID_H_
55