Add CreateTaskQueue for early initialization
[platform/core/api/webapi-plugins.git] / src / common / task-queue.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16
17 #include "task-queue.h"
18
19 namespace common {
20
21 TaskQueue& TaskQueue::GetInstance() {
22   static TaskQueue task_queue;
23   return task_queue;
24 }
25
26 template <>
27 gboolean TaskQueue::WorkCallback<void>(gpointer data) {
28   QueueData<void>* d = static_cast<QueueData<void>*>(data);
29   if (nullptr != d) {
30     d->work_callback_();
31     delete d;
32   }
33   return FALSE;
34 }
35
36 void TaskQueue::Queue(const std::function<void()>& work, const std::function<void()>& after_work) {
37   auto do_work = [work, after_work]() {
38     work();
39     after_work();
40   };
41   this->queue_worker_.add_job(do_work);
42 }
43
44 void TaskQueue::Async(const std::function<void()>& work) {
45   this->async_worker_.add_job(work);
46 }
47
48 void TaskQueue::Async(const std::function<void(const common::AsyncToken& token)>& work,
49                       const common::AsyncToken& token) {
50   auto do_work = [work, token]() { work(token); };
51   Async(do_work);
52 }
53
54 void TaskQueue::DeleteJobs() {
55   {
56     std::lock_guard<std::mutex> lck{this->queue_worker_.jobs_mtx};
57     this->queue_worker_.jobs.clear();
58   }
59   {
60     std::lock_guard<std::mutex> lck{this->async_worker_.jobs_mtx};
61     this->async_worker_.jobs.clear();
62   }
63 }
64
65 void TaskQueue::Stop() {
66   LoggerI("Stopping TaskQueue workers");
67   queue_worker_.stop();
68   async_worker_.stop();
69 }
70
71 void TaskQueue::ScheduleWorkInMainThread(const std::function<void()>& work) {
72   QueueData<void>* d = new QueueData<void>();
73   d->work_callback_ = work;
74   if (!g_idle_add(WorkCallback<void>, d)) {
75     LoggerE("g_idle_add failed");
76     delete d;
77   }
78 }
79
80 }  // namespace common
81
82 extern "C" {
83
84 __attribute__ ((visibility("default"))) void CreateTaskQueue() {
85   common::TaskQueue::GetInstance();
86   LoggerI("Create TaskQueue");
87 }
88
89 }