1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 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 * http://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 16 #ifndef FFRT_WORKER_THREAD_HPP 17 #define FFRT_WORKER_THREAD_HPP 18 19 #include <atomic> 20 #include <thread> 21 22 #include "sched/qos.h" 23 #include "core/task_ctx.h" 24 25 namespace ffrt { 26 class WorkerThread { 27 public: 28 TaskCtx* curTask = nullptr; WorkerThread(const QoS & qos)29 explicit WorkerThread(const QoS& qos) : exited(false), idle(false), tid(-1), qos(qos) 30 { 31 } 32 ~WorkerThread()33 virtual ~WorkerThread() 34 { 35 Join(); 36 } 37 Idle()38 bool Idle() const 39 { 40 return idle; 41 } 42 SetIdle(bool var)43 void SetIdle(bool var) 44 { 45 this->idle = var; 46 } 47 Exited()48 bool Exited() const 49 { 50 return exited; 51 } 52 SetExited(bool var)53 void SetExited(bool var) 54 { 55 this->exited = var; 56 } 57 Id()58 pid_t Id() const 59 { 60 while (!exited && tid < 0) { 61 } 62 return tid; 63 } 64 GetQos()65 const QoS& GetQos() const 66 { 67 return qos; 68 } 69 70 template <typename F, typename... Args> Start(F && f,Args &&...args)71 void Start(F&& f, Args&&... args) 72 { 73 auto wrap = [&](Args&&... args) { 74 NativeConfig(); 75 return f(args...); 76 }; 77 thread = std::thread(wrap, args...); 78 } 79 Join()80 void Join() 81 { 82 if (thread.joinable()) { 83 thread.join(); 84 } 85 tid = -1; 86 } 87 Detach()88 void Detach() 89 { 90 if (thread.joinable()) { 91 thread.detach(); 92 } 93 tid = -1; 94 } 95 GetThread()96 std::thread& GetThread() 97 { 98 return this->thread; 99 } 100 101 void WorkerSetup(WorkerThread* wthread, const QoS& qos); 102 private: 103 void NativeConfig(); 104 105 std::atomic_bool exited; 106 std::atomic_bool idle; 107 108 std::atomic<pid_t> tid; 109 110 QoS qos; 111 std::thread thread; 112 }; 113 } // namespace ffrt 114 #endif 115