Fix third start fails
[platform/core/system/swap-manager.git] / daemon / cpp / events / evloop_request.h
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved.
3  *
4  * Contact:
5  *      Vyacheslav Cherkashin <v.cherkashin@samsung.com>
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * Contributors:
20  * - Samsung RnD Institute Russia
21  *
22  */
23
24
25 #ifndef EVLOOP_REQUEST_H
26 #define EVLOOP_REQUEST_H
27
28
29 #include <queue>
30 #include <memory>
31 #include <swap_debug.h>
32
33
34 namespace EvLoop {
35
36
37 class Request {
38 public:
39     virtual ~Request() {}
40     void execute()
41     {
42         try {
43             do_execute();
44         } catch (const std::runtime_error &e) {
45             LOGE("%s\n", e.what());
46         } catch (...) {
47             LOGE("Unknown error\n");
48         }
49     }
50
51 private:
52     virtual void do_execute() = 0;
53 };
54
55
56 class RequestQueue {
57 public:
58     void push(std::unique_ptr<Request> &req)
59     {
60         std::lock_guard<std::mutex> lock(req_queue_mutex_);
61         req_queue_.push(std::move(req));
62     }
63
64     void do_all()
65     {
66         req_queue_mutex_.lock();
67         while (!req_queue_.empty()) {
68             auto req = std::move(req_queue_.front());
69             req_queue_.pop();
70             req_queue_mutex_.unlock();
71
72             req->execute();
73
74             req_queue_mutex_.lock();
75         }
76         req_queue_mutex_.unlock();
77     }
78
79     bool empty()
80     {
81         std::lock_guard<std::mutex> lock(req_queue_mutex_);
82         return req_queue_.empty();
83     }
84
85 private:
86     std::queue<std::unique_ptr<Request>> req_queue_;
87     std::mutex req_queue_mutex_;
88 };
89
90
91 } // namespace EvLoop
92
93 #endif // EVLOOP_REQUEST_H