/home/docs/checkouts/readthedocs.org/user_builds/advanced-micro-devices-composable-kernel/checkouts/develop/include/ck_tile/host/joinable_thread.hpp Source File

/home/docs/checkouts/readthedocs.org/user_builds/advanced-micro-devices-composable-kernel/checkouts/develop/include/ck_tile/host/joinable_thread.hpp Source File#

Composable Kernel: /home/docs/checkouts/readthedocs.org/user_builds/advanced-micro-devices-composable-kernel/checkouts/develop/include/ck_tile/host/joinable_thread.hpp Source File
joinable_thread.hpp
Go to the documentation of this file.
1 // Copyright (c) Advanced Micro Devices, Inc., or its affiliates.
2 // SPDX-License-Identifier: MIT
3 
4 #pragma once
5 
6 #ifdef __linux__
7 #include <sched.h>
8 #endif
9 #include <thread>
10 #include <utility>
11 
12 namespace ck_tile {
13 
14 struct joinable_thread : std::thread
15 {
16  template <typename... Xs>
17  joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...)
18  {
19  }
20 
23 
25  {
26  if(this->joinable())
27  this->join();
28  }
29 };
30 
31 inline unsigned int get_available_cpu_cores()
32 {
33 #if defined(__linux__)
34  cpu_set_t cpu_set;
35  if(sched_getaffinity(0, sizeof(cpu_set_t), &cpu_set) == 0)
36  {
37  unsigned int cpu_count = CPU_COUNT(&cpu_set);
38  if(cpu_count > 0)
39  return cpu_count;
40  }
41 #endif
42  // Fallback if sched_getaffinity unavailable or fails
43  return std::thread::hardware_concurrency();
44 }
45 
47 {
48 #if defined(__linux__)
49  cpu_set_t original_cpu_set_;
50 
51  public:
52  cpu_core_guard(unsigned int num_cores) : original_cpu_set_()
53  {
54  // save original cpu set
55  sched_getaffinity(0, sizeof(cpu_set_t), &original_cpu_set_);
56 
57  // set new cpu set
58  cpu_set_t new_cpu_set;
59  CPU_ZERO(&new_cpu_set);
60  for(unsigned int i = 0; i < num_cores; ++i)
61  {
62 #pragma clang diagnostic push
63 #pragma clang diagnostic ignored "-Wold-style-cast"
64  CPU_SET(i, &new_cpu_set); // NOLINT(old-style-cast)
65 #pragma clang diagnostic pop
66  }
67  sched_setaffinity(0, sizeof(cpu_set_t), &new_cpu_set);
68  }
70  {
71  // restore original cpu set
72  sched_setaffinity(0, sizeof(cpu_set_t), &original_cpu_set_);
73  }
74 #endif
75 };
76 } // namespace ck_tile
Definition: joinable_thread.hpp:47
Definition: cluster_descriptor.hpp:13
unsigned int get_available_cpu_cores()
Definition: joinable_thread.hpp:31
Definition: joinable_thread.hpp:15
joinable_thread(Xs &&... xs)
Definition: joinable_thread.hpp:17
~joinable_thread()
Definition: joinable_thread.hpp:24
joinable_thread & operator=(joinable_thread &&)=default
joinable_thread(joinable_thread &&)=default