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 #include <random>
17
18 #include <gtest/gtest.h>
19
20 #include "internal_inc/config.h"
21 #include "eu/cpu_worker.h"
22 #include "eu/cpu_monitor.h"
23 #include "core/entity.h"
24 #include "sched/scheduler.h"
25 #include "../common.h"
26
27 using namespace std;
28 using namespace testing;
29 #ifdef HWTEST_TESTING_EXT_ENABLE
30 using namespace testing::ext;
31 #endif
32 using namespace ffrt;
33
34 class ExecuteUnitTest : public testing::Test {
35 protected:
SetUpTestCase()36 static void SetUpTestCase()
37 {
38 }
39
TearDownTestCase()40 static void TearDownTestCase()
41 {
42 }
43
SetUp()44 virtual void SetUp()
45 {
46 }
47
TearDown()48 virtual void TearDown()
49 {
50 }
51 };
52
53 // 提交、取消并行普通/延时任务成功
HWTEST_F(ExecuteUnitTest, submit_cancel_succ, TestSize.Level1)54 HWTEST_F(ExecuteUnitTest, submit_cancel_succ, TestSize.Level1)
55 {
56 std::atomic<int> x = 0;
57 ffrt::submit([&]() { x.fetch_add(1); });
58 ffrt::submit([&]() { x.fetch_add(2); }, {}, {}, ffrt::task_attr().delay(1));
59 auto h1 = ffrt::submit_h([&]() { x.fetch_add(3); });
60 auto h2 = ffrt::submit_h([&]() { x.fetch_add(4); }, {}, {}, ffrt::task_attr().delay(2));
61 int cancel_ret = ffrt::skip(h2);
62 EXPECT_EQ(cancel_ret, 0);
63 ffrt::wait();
64 EXPECT_EQ(x.load(), 6);
65 }
66
67 // 提交、取消并行普通/延时任务成功
HWTEST_F(ExecuteUnitTest, submit_cancel_failed, TestSize.Level1)68 HWTEST_F(ExecuteUnitTest, submit_cancel_failed, TestSize.Level1)
69 {
70 int x = 0;
71 auto h1 = ffrt::submit_h([&]() { x += 1; });
72 auto h2 = ffrt::submit_h([&]() { x += 2; }, {&x}, {&x}, ffrt::task_attr().delay(1));
73 int cancel_ret = ffrt::skip(h2);
74 EXPECT_EQ(cancel_ret, 0);
75 ffrt::wait();
76 EXPECT_EQ(x, 1);
77
78 cancel_ret = ffrt::skip(h1);
79 EXPECT_EQ(cancel_ret, -1);
80 ffrt::task_handle h3;
81 cancel_ret = ffrt::skip(h3);
82 EXPECT_EQ(cancel_ret, 22);
83 }
84