Line data Source code
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/atomicops.h"
9 :
10 : namespace v8 {
11 : namespace internal {
12 :
13 : // Platform-independent, reliable thread identifier.
14 : class ThreadId {
15 : public:
16 : // Creates an invalid ThreadId.
17 61049 : ThreadId() { base::Relaxed_Store(&id_, kInvalidId); }
18 :
19 576011 : ThreadId& operator=(const ThreadId& other) V8_NOEXCEPT {
20 1152022 : base::Relaxed_Store(&id_, base::Relaxed_Load(&other.id_));
21 576011 : return *this;
22 : }
23 :
24 : bool operator==(const ThreadId& other) const { return Equals(other); }
25 :
26 : // Returns ThreadId for current thread if it exists or invalid id.
27 : static ThreadId TryGetCurrent();
28 :
29 : // Returns ThreadId for current thread.
30 1293834 : static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }
31 :
32 : // Returns invalid ThreadId (guaranteed not to be equal to any thread).
33 473703 : static ThreadId Invalid() { return ThreadId(kInvalidId); }
34 :
35 : // Compares ThreadIds for equality.
36 : V8_INLINE bool Equals(const ThreadId& other) const {
37 433758 : return base::Relaxed_Load(&id_) == base::Relaxed_Load(&other.id_);
38 : }
39 :
40 : // Checks whether this ThreadId refers to any thread.
41 : V8_INLINE bool IsValid() const {
42 31301 : return base::Relaxed_Load(&id_) != kInvalidId;
43 : }
44 :
45 : // Converts ThreadId to an integer representation
46 : // (required for public API: V8::V8::GetCurrentThreadId).
47 446264 : int ToInteger() const { return static_cast<int>(base::Relaxed_Load(&id_)); }
48 :
49 : // Converts ThreadId to an integer representation
50 : // (required for public API: V8::V8::TerminateExecution).
51 : static ThreadId FromInteger(int id) { return ThreadId(id); }
52 :
53 : private:
54 : static const int kInvalidId = -1;
55 :
56 : explicit ThreadId(int id) { base::Relaxed_Store(&id_, id); }
57 :
58 : static int AllocateThreadId() {
59 : int new_id = base::Relaxed_AtomicIncrement(&highest_thread_id_, 1);
60 : return new_id;
61 : }
62 :
63 : static int GetCurrentThreadId();
64 :
65 : base::Atomic32 id_;
66 :
67 : static base::Atomic32 highest_thread_id_;
68 : };
69 :
70 : } // namespace internal
71 : } // namespace v8
72 :
73 : #endif // V8_THREAD_ID_H_
|