1 /**
2 * Copyright (c) 2021-2022 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 #include "runtime/scheduler/task.h"
17 #include "runtime/scheduler/worker_thread.h"
18 #include "runtime/include/runtime.h"
19 #include "runtime/include/panda_vm.h"
20
21 namespace panda::scheduler {
22
23 // TODO(xuliang): task id
Task(PandaVM * vm,ObjectHeader * obj)24 Task::Task(PandaVM *vm, ObjectHeader *obj)
25 : ManagedThread(-1, Runtime::GetCurrent()->GetInternalAllocator(), vm, Thread::ThreadType::THREAD_TYPE_TASK)
26 {
27 future = obj;
28 }
29
Create(PandaVM * vm,ObjectHeader * obj)30 Task *Task::Create(PandaVM *vm, ObjectHeader *obj)
31 {
32 auto allocator = Runtime::GetCurrent()->GetInternalAllocator();
33 auto *task = allocator->New<Task>(vm, obj);
34 task->Initialize();
35 return task;
36 }
37
Initialize()38 void Task::Initialize()
39 {
40 trace::ScopedTrace scoped_trace2("ThreadManager::RegisterThread");
41 // TODO(xuliang): RegisterThread
42 }
43
Destroy()44 void Task::Destroy()
45 {
46 ASSERT(this == Task::GetCurrent());
47 // TODO(xuliang): should be done in UnregisterExitedThread.
48 auto allocator = Runtime::GetCurrent()->GetInternalAllocator();
49 auto wt = workerThread;
50 allocator->Delete(this);
51 Thread::SetCurrent(wt);
52 }
53
SwitchFromWorkerThread()54 void Task::SwitchFromWorkerThread()
55 {
56 workerThread = WorkerThread::GetCurrent();
57 workerThread->SetTask(this);
58 Thread::SetCurrent(this);
59 }
60
SuspendCurrent()61 void Task::SuspendCurrent()
62 {
63 auto task = Task::GetCurrent();
64 auto wt = task->workerThread;
65 ASSERT(wt != nullptr);
66 Thread::SetCurrent(wt);
67 wt->SetTask(nullptr);
68 }
69
EndCurrent()70 void Task::EndCurrent()
71 {
72 auto task = Task::GetCurrent();
73 auto wt = task->workerThread;
74 ASSERT(wt != nullptr);
75 task->Destroy();
76 Thread::SetCurrent(wt);
77 wt->SetTask(nullptr);
78 }
79
80 } // namespace panda::scheduler
81