thread-id.h 1.62 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 6
#ifndef V8_EXECUTION_THREAD_ID_H_
#define V8_EXECUTION_THREAD_ID_H_
7

8 9
#include "src/base/macros.h"

10 11 12 13 14 15 16
namespace v8 {
namespace internal {

// Platform-independent, reliable thread identifier.
class ThreadId {
 public:
  // Creates an invalid ThreadId.
Clemens Hammacher's avatar
Clemens Hammacher committed
17
  constexpr ThreadId() noexcept : ThreadId(kInvalidId) {}
18

Clemens Hammacher's avatar
Clemens Hammacher committed
19 20
  bool operator==(const ThreadId& other) const { return id_ == other.id_; }
  bool operator!=(const ThreadId& other) const { return id_ != other.id_; }
21

Clemens Hammacher's avatar
Clemens Hammacher committed
22 23
  // Checks whether this ThreadId refers to any thread.
  bool IsValid() const { return id_ != kInvalidId; }
24

Clemens Hammacher's avatar
Clemens Hammacher committed
25 26
  // Converts ThreadId to an integer representation.
  constexpr int ToInteger() const { return id_; }
27 28 29 30 31 32 33 34

  // Returns ThreadId for current thread if it exists or invalid id.
  static ThreadId TryGetCurrent();

  // Returns ThreadId for current thread.
  static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }

  // Returns invalid ThreadId (guaranteed not to be equal to any thread).
Clemens Hammacher's avatar
Clemens Hammacher committed
35
  static constexpr ThreadId Invalid() { return ThreadId(kInvalidId); }
36 37 38

  // Converts ThreadId to an integer representation
  // (required for public API: V8::V8::TerminateExecution).
Clemens Hammacher's avatar
Clemens Hammacher committed
39
  static constexpr ThreadId FromInteger(int id) { return ThreadId(id); }
40 41

 private:
42
  static constexpr int kInvalidId = -1;
43

Clemens Hammacher's avatar
Clemens Hammacher committed
44
  explicit constexpr ThreadId(int id) noexcept : id_(id) {}
45

46
  V8_EXPORT_PRIVATE static int GetCurrentThreadId();
47

Clemens Hammacher's avatar
Clemens Hammacher committed
48
  int id_;
49 50 51 52 53
};

}  // namespace internal
}  // namespace v8

54
#endif  // V8_EXECUTION_THREAD_ID_H_