report-json-serializer: app and top serializers
[apps/native/ttsd-worker-task.git] / src / worker.c
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Flora License, Version 1.1 (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://floralicense.org/license/
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 <glib.h>
18
19 #include "worker.h"
20 #include "task.h"
21 #include "log.h"
22 #include "err-check.h"
23
24 #define THREADS_NO_LIMIT -1
25
26 static void worker_function(gpointer data, gpointer user_data);
27
28 struct worker
29 {
30     GThreadPool *thread_pool;
31 };
32
33 worker_t *worker_create()
34 {
35     GError *err = NULL;
36     struct worker *_worker = g_malloc(sizeof(struct worker));
37
38     _worker->thread_pool = g_thread_pool_new((GFunc)worker_function, NULL, THREADS_NO_LIMIT, FALSE, &err);
39     if (err != NULL)
40     {
41         ERR("Failed to create thread pool ", err->message);
42         g_error_free (err);
43         g_free(_worker);
44         return NULL;
45     }
46     return _worker;
47 }
48
49 void worker_destroy(worker_t *worker)
50 {
51     ON_NULL_RETURN(worker);
52
53     g_thread_pool_free (worker->thread_pool, FALSE, TRUE);
54     g_free(worker);
55 }
56
57 void worker_sync(worker_t *worker)
58 {
59     GError *err = NULL;
60
61     g_thread_pool_free(worker->thread_pool, FALSE, TRUE);
62     worker->thread_pool = g_thread_pool_new((GFunc)worker_function, NULL, THREADS_NO_LIMIT, FALSE, &err);
63     if (err != NULL)
64     {
65         ERR("Failed to create thread pool ", err->message);
66         g_error_free (err);
67         return;
68     }
69 }
70
71 void worker_set_max_num_of_threads(worker_t *worker, int max_threads)
72 {
73     ON_NULL_RETURN(worker);
74
75     GError *err = NULL;
76     g_thread_pool_set_max_threads(worker->thread_pool, max_threads, &err);
77     if (err != NULL)
78     {
79         ERR("Failed to set maximum threads for given pool ", err->message);
80         g_error_free (err);
81     }
82 }
83
84 int worker_enqueue_task(worker_t *worker, task_t *task)
85 {
86     ON_NULL_RETURN_VAL(worker, -1);
87
88     return g_thread_pool_push(worker->thread_pool, task, NULL);
89 }
90
91 static void worker_function(gpointer data, gpointer user_data)
92 {
93     task_t *task = (task_t *)data;
94     task_execute(task);
95 }