• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef SANDBOXED_API_UTIL_THREAD_H_
16 #define SANDBOXED_API_UTIL_THREAD_H_
17 
18 #include <memory>
19 #include <utility>
20 #include <thread>
21 
22 #include "absl/functional/any_invocable.h"
23 #include "absl/strings/string_view.h"
24 
25 namespace sapi {
26 
27 class Thread {
28  public:
29   static void StartDetachedThread(absl::AnyInvocable<void() &&> functor,
30                                   absl::string_view name_prefix = "") {
31     std::thread(std::move(functor)).detach();
32   }
33 
34   Thread() = default;
35 
36   Thread(const Thread&) = delete;
37   Thread& operator=(const Thread&) = delete;
38 
39   Thread(Thread&&) = default;
40   Thread& operator=(Thread&&) = default;
41 
42   Thread(absl::AnyInvocable<void() &&> functor,
43          absl::string_view name_prefix = "") {
44     thread_ = std::thread(std::move(functor));
45   }
46 
47   template <class CL>
48   Thread(CL* ptr, void (CL::*ptr_to_member)(),
49          absl::string_view name_prefix = "") {
50     thread_ = std::thread(ptr_to_member, ptr);
51   }
52 
handle()53   pthread_t handle() {
54     return thread_.native_handle();
55   }
56 
Join()57   void Join() {
58     thread_.join();
59   }
60 
IsJoinable()61   bool IsJoinable() {
62     return thread_.joinable();
63   }
64 
65  private:
66   std::thread thread_;
67 };
68 
69 }  // namespace sapi
70 
71 #endif  // SANDBOXED_API_UTIL_THREAD_H_
72