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     constexpr static uint16_t TASK_QUEUE_CAPACITY = 10240;
22 }
23 
AbilityEventHandler()24 AbilityEventHandler::AbilityEventHandler()
25 {
26     g_currentHandler = this;
27     (void) pthread_mutex_init(&queueMutex_, nullptr);
28     (void) pthread_cond_init(&pthreadCond_, nullptr);
29 }
30 
~AbilityEventHandler()31 AbilityEventHandler::~AbilityEventHandler()
32 {
33     (void) pthread_mutex_destroy(&queueMutex_);
34     (void) pthread_cond_destroy(&pthreadCond_);
35 
36     g_currentHandler = nullptr;
37 }
38 
Run()39 void AbilityEventHandler::Run()
40 {
41     (void) pthread_mutex_lock(&queueMutex_);
42     while (!quit_) {
43         if (taskQueue_.empty()) {
44             (void) pthread_cond_wait(&pthreadCond_, &queueMutex_);
45         }
46         Task task = std::move(taskQueue_.front());
47         taskQueue_.pop();
48         (void) pthread_mutex_unlock(&queueMutex_);
49         task();
50         (void) pthread_mutex_lock(&queueMutex_);
51     }
52     (void) pthread_mutex_unlock(&queueMutex_);
53 }
54 
PostTask(const Task & task)55 void AbilityEventHandler::PostTask(const Task& task)
56 {
57     if (taskQueue_.size() >= TASK_QUEUE_CAPACITY) {
58         return;
59     }
60     (void) pthread_mutex_lock(&queueMutex_);
61     taskQueue_.push(task);
62 
63     (void) pthread_cond_signal(&pthreadCond_);
64     (void) pthread_mutex_unlock(&queueMutex_);
65 }
66 
PostQuit()67 void AbilityEventHandler::PostQuit()
68 {
69     Task task = [this]() {
70         quit_ = true;
71     };
72     PostTask(task);
73 }
74 
GetCurrentHandler()75 AbilityEventHandler* AbilityEventHandler::GetCurrentHandler()
76 {
77     return g_currentHandler;
78 }
79 }  // namespace OHOS