• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2020 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 "ability_event_handler.h"
17 
18 namespace OHOS {
19 namespace {
20     thread_local AbilityEventHandler* g_currentHandler;
21 }
22 
AbilityEventHandler()23 AbilityEventHandler::AbilityEventHandler()
24 {
25     g_currentHandler = this;
26     (void) pthread_mutex_init(&queueMutex_, nullptr);
27     (void) pthread_cond_init(&pthreadCond_, nullptr);
28 }
29 
~AbilityEventHandler()30 AbilityEventHandler::~AbilityEventHandler()
31 {
32     (void) pthread_mutex_destroy(&queueMutex_);
33     (void) pthread_cond_destroy(&pthreadCond_);
34 
35     g_currentHandler = nullptr;
36 }
37 
Run()38 void AbilityEventHandler::Run()
39 {
40     (void) pthread_mutex_lock(&queueMutex_);
41     while (!quit_) {
42         if (taskQueue_.empty()) {
43             (void) pthread_cond_wait(&pthreadCond_, &queueMutex_);
44         }
45         Task task = std::move(taskQueue_.front());
46         taskQueue_.pop();
47         (void) pthread_mutex_unlock(&queueMutex_);
48         task();
49         (void) pthread_mutex_lock(&queueMutex_);
50     }
51     (void) pthread_mutex_unlock(&queueMutex_);
52 }
53 
PostTask(const Task & task)54 void AbilityEventHandler::PostTask(const Task& task)
55 {
56     (void) pthread_mutex_lock(&queueMutex_);
57     taskQueue_.push(task);
58 
59     (void) pthread_cond_signal(&pthreadCond_);
60     (void) pthread_mutex_unlock(&queueMutex_);
61 }
62 
PostQuit()63 void AbilityEventHandler::PostQuit()
64 {
65     Task task = [this]() {
66         quit_ = true;
67     };
68     PostTask(task);
69 }
70 
GetCurrentHandler()71 AbilityEventHandler* AbilityEventHandler::GetCurrentHandler()
72 {
73     return g_currentHandler;
74 }
75 }  // namespace OHOS