d232149b82f64caa3e075f58997a019011b7926f
[platform/core/uifw/lottie-player.git] / src / vector / vtaskqueue.h
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved.
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 #ifndef VTASKQUEUE_H
18 #define VTASKQUEUE_H
19
20 #include <deque>
21
22 template <typename Task>
23 class TaskQueue {
24     using lock_t = std::unique_lock<std::mutex>;
25     std::deque<Task>      _q;
26     bool                    _done{false};
27     std::mutex              _mutex;
28     std::condition_variable _ready;
29
30 public:
31     bool try_pop(Task &task)
32     {
33         lock_t lock{_mutex, std::try_to_lock};
34         if (!lock || _q.empty()) return false;
35         task = std::move(_q.front());
36         _q.pop_front();
37         return true;
38     }
39
40     bool try_push(Task &&task)
41     {
42         {
43             lock_t lock{_mutex, std::try_to_lock};
44             if (!lock) return false;
45             _q.push_back(std::move(task));
46         }
47         _ready.notify_one();
48         return true;
49     }
50
51     void done()
52     {
53         {
54             lock_t lock{_mutex};
55             _done = true;
56         }
57         _ready.notify_all();
58     }
59
60     bool pop(Task &task)
61     {
62         lock_t lock{_mutex};
63         while (_q.empty() && !_done) _ready.wait(lock);
64         if (_q.empty()) return false;
65         task = std::move(_q.front());
66         _q.pop_front();
67         return true;
68     }
69
70     void push(Task &&task)
71     {
72         {
73             lock_t lock{_mutex};
74             _q.push_back(std::move(task));
75         }
76         _ready.notify_one();
77     }
78
79 };
80
81 #endif  // VTASKQUEUE_H