1 /**
2 * Copyright (c) 2021-2024 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 <gtest/gtest.h>
17
18 #include "libpandabase/utils/utf.h"
19 #include "libpandabase/panda_gen_options/generated/base_options.h"
20 #include "runtime/include/class_linker.h"
21 #include "runtime/include/runtime.h"
22 #include "runtime/scheduler/worker_thread.h"
23 #include "runtime/scheduler/task.h"
24 #include "runtime/tests/class_linker_test_extension.h"
25
26 namespace ark::scheduler::test {
27
28 class WorkerThreadTest : public testing::Test {
29 public:
WorkerThreadTest()30 WorkerThreadTest()
31 {
32 Logger::Initialize(base_options::Options(""));
33
34 RuntimeOptions options;
35 auto execPath = ark::os::file::File::GetExecutablePath();
36 std::string pandaStdLib = execPath.Value() + "/../pandastdlib/arkstdlib.abc";
37 options.SetBootPandaFiles({pandaStdLib});
38 Runtime::Create(options);
39 mainThread_ = Thread::GetCurrent();
40 Thread::SetCurrent(nullptr);
41 }
42
~WorkerThreadTest()43 ~WorkerThreadTest() override
44 {
45 Thread::SetCurrent(mainThread_);
46 Runtime::Destroy();
47 }
48
49 NO_COPY_SEMANTIC(WorkerThreadTest);
50 NO_MOVE_SEMANTIC(WorkerThreadTest);
51
52 private:
53 Thread *mainThread_ = nullptr;
54 };
55
TEST_F(WorkerThreadTest,SwitchTasksInOneWorkerThread)56 TEST_F(WorkerThreadTest, SwitchTasksInOneWorkerThread)
57 {
58 auto wt = WorkerThread::AttachThread();
59 ASSERT_EQ(wt, WorkerThread::GetCurrent());
60 auto tk1 = Task::Create(Runtime::GetCurrent()->GetPandaVM());
61
62 tk1->SwitchFromWorkerThread();
63 ASSERT_EQ(tk1, Task::GetCurrent());
64 auto tk2 = Task::Create(Runtime::GetCurrent()->GetPandaVM());
65 Task::SuspendCurrent();
66
67 tk2->SwitchFromWorkerThread();
68 ASSERT_EQ(tk2, Task::GetCurrent());
69 Task::EndCurrent();
70
71 tk1->SwitchFromWorkerThread();
72 Task::EndCurrent();
73
74 WorkerThread::DetachThread();
75 }
76
77 } // namespace ark::scheduler::test
78