1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // WARNING: *DO NOT* use this class directly. base::PlatformThreadRef is a
6 // low-level platform-specific abstraction to the OS's threading interface.
7 // Instead, consider using a message-loop driven base::Thread, see
8 // base/threading/thread.h.
9 
10 #ifndef PARTITION_ALLOC_PARTITION_ALLOC_BASE_THREADING_PLATFORM_THREAD_REF_H_
11 #define PARTITION_ALLOC_PARTITION_ALLOC_BASE_THREADING_PLATFORM_THREAD_REF_H_
12 
13 #include <iosfwd>
14 
15 #include "build/build_config.h"
16 #include "partition_alloc/partition_alloc_base/component_export.h"
17 
18 #if BUILDFLAG(IS_WIN)
19 #include "partition_alloc/partition_alloc_base/win/windows_types.h"
20 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
21 #include <pthread.h>
22 #endif
23 
24 namespace partition_alloc::internal::base {
25 
26 // Used for thread checking and debugging.
27 // Meant to be as fast as possible.
28 // These are produced by PlatformThread::CurrentRef(), and used to later
29 // check if we are on the same thread or not by using ==. These are safe
30 // to copy between threads, but can't be copied to another process as they
31 // have no meaning there. Also, the internal identifier can be re-used
32 // after a thread dies, so a PlatformThreadRef cannot be reliably used
33 // to distinguish a new thread from an old, dead thread.
34 class PlatformThreadRef {
35  public:
36 #if BUILDFLAG(IS_WIN)
37   using RefType = DWORD;
38 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
39   using RefType = pthread_t;
40 #endif
41 
42   constexpr PlatformThreadRef() = default;
PlatformThreadRef(RefType id)43   explicit constexpr PlatformThreadRef(RefType id) : id_(id) {}
44 
45   bool operator==(PlatformThreadRef other) const { return id_ == other.id_; }
46   bool operator!=(PlatformThreadRef other) const { return id_ != other.id_; }
47 
is_null()48   bool is_null() const { return id_ == 0; }
49 
50  private:
51   RefType id_ = 0;
52 };
53 
54 }  // namespace partition_alloc::internal::base
55 
56 #endif  // PARTITION_ALLOC_PARTITION_ALLOC_BASE_THREADING_PLATFORM_THREAD_REF_H_
57