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 _TASK_BASE_H_
17 #define _TASK_BASE_H_
18 #include <atomic>
19 #include <vector>
20 #include "eu/co_routine.h"
21 #include "qos.h"
22 #include "sched/execute_ctx.h"
23 #include "util/task_deleter.h"
24 
25 namespace ffrt {
26 static std::atomic_uint64_t s_gid(0);
27 class TaskBase {
28 public:
29     uintptr_t reserved = 0;
30     uintptr_t type = 0;
31     WaitEntry fq_we; // used on fifo fast que
TaskBase()32     TaskBase(): gid(++s_gid) {}
33     virtual ~TaskBase() = default;
34     const uint64_t gid; // global unique id in this process
35 #ifdef FFRT_ASYNC_STACKTRACE
36     uint64_t stackId = 0;
37 #endif
38 
GetQos() const39     virtual int GetQos() const
40     {
41         return qos_default;
42     }
43 
44 #if (FFRT_TRACE_RECORD_LEVEL >= FFRT_TRACE_RECORD_LEVEL_1)
45     uint64_t createTime;
46     uint64_t executeTime;
47 #endif
48     int32_t fromTid;
49 };
50 
51 class CoTask : public TaskBase, public TaskDeleter {
52 public:
53     CoTask() = default;
54     ~CoTask() override = default;
55     virtual void Execute() = 0;
56 
57     std::string label;
58     std::vector<std::string> traceTag;
59     bool wakeupTimeOut = false;
60     int cpuBoostCtxId = -1;
61     WaitUntilEntry* wue = nullptr;
62     // lifecycle connection between task and coroutine is shown as below:
63     // |*task pending*|*task ready*|*task executing*|*task done*|*task release*|
64     //                             |**********coroutine*********|
65     CoRoutine* coRoutine = nullptr;
66     uint64_t stack_size = STACK_SIZE;
67     std::atomic<pthread_t> runningTid = 0;
68     int legacyCountNum = 0; // dynamic switch controlled by set_legacy_mode api
69     BlockType blockType { BlockType::BLOCK_COROUTINE }; // block type for lagacy mode changing
70     std::mutex mutex_; // used in coroute
71     std::condition_variable waitCond_; // cv for thread wait
72 
SetTraceTag(const char* name)73     void SetTraceTag(const char* name)
74     {
75         traceTag.emplace_back(name);
76     }
77 
ClearTraceTag()78     void ClearTraceTag()
79     {
80         if (!traceTag.empty()) {
81             traceTag.pop_back();
82         }
83     }
84 };
85 }
86 #endif