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 "sync_task.h"
17 #include <thread>
18
19 namespace OHOS {
20 namespace AppExecFwk {
21 // Help to calculate hash code of object.
22 template<typename T>
CalculateHashCode(const T & obj)23 inline size_t CalculateHashCode(const T &obj)
24 {
25 std::hash<T> calculateHashCode;
26 return calculateHashCode(obj);
27 }
28
SyncTask(const std::shared_ptr<Runnable> & runnable,TaskPriority priority,const std::shared_ptr<BaseTaskDispatcher> & baseTaskDispatcher)29 SyncTask::SyncTask(const std::shared_ptr<Runnable> &runnable, TaskPriority priority,
30 const std::shared_ptr<BaseTaskDispatcher> &baseTaskDispatcher)
31 : Task(runnable, priority, baseTaskDispatcher)
32 {
33 executed_.store(false);
34 }
35
Run()36 void SyncTask::Run()
37 {
38 std::unique_lock<std::mutex> lock(mutex_);
39 auto threadId = std::this_thread::get_id();
40 HILOG_INFO("SyncTask::Run begin thread=%{public}zu", CalculateHashCode(threadId));
41 Task::Run();
42 executed_.store(true);
43
44 // |waitTask| may have been multi invoked.
45 condition_variable_.notify_all();
46 HILOG_INFO("SyncTask::Run end thread=%{public}zu", CalculateHashCode(threadId));
47 }
48
WaitTask()49 void SyncTask::WaitTask()
50 {
51 auto threadId = std::this_thread::get_id();
52 HILOG_INFO("SyncTask::WaitTask begin thread=%{public}zu", CalculateHashCode(threadId));
53
54 std::unique_lock<std::mutex> lock(mutex_);
55 while (executed_ == false) {
56 condition_variable_.wait(lock);
57 }
58
59 HILOG_INFO("SyncTask::WaitTask end thread=%{public}zu", CalculateHashCode(threadId));
60 }
61
62 } // namespace AppExecFwk
63 } // namespace OHOS
64