1 /*
2  * Copyright (c) 2020-2021 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 #ifndef OHOS_EVENTHANDLER_H
17 #define OHOS_EVENTHANDLER_H
18 
19 #include <thread>
20 #include <mutex>
21 #include <queue>
22 #include <condition_variable>
23 
24 namespace OHOS {
25 namespace Media {
26 class EventHandler {
27 public:
28     EventHandler();
29     virtual ~EventHandler();
30     /* After construct the event handler, user should check whether the thread is running before post or
31      * destroy this handler */
32     bool IsRunning();
33 
34     template<typename F>
Post(const F & f)35     void Post(const F &f)
36     {
37         auto task = new PostTask<F>(f);
38         std::unique_lock<std::mutex> lock(mtx_);
39         msgQ_.emplace(task);
40         cv_.notify_all();
41     }
42 
43 private:
44     struct EventObj {
45         EventObj() = default;
~EventObjEventObj46         virtual ~EventObj() {}
ExecEventObj47         virtual void Exec() {}
48     };
49 
50     std::queue<EventObj *> msgQ_;
51     std::thread *hdlThrd_;
52     bool running_;
53     std::condition_variable cv_;
54     std::mutex mtx_;
55 
56     template<typename F>
57     struct PostTask : public EventObj {
PostTaskPostTask58         explicit PostTask(const F &f) : f_(f) {}
59         const F f_;
ExecPostTask60         void Exec() override
61         {
62             f_();
63         }
64     };
65 
66     static void EventDispatch(EventHandler *hdl);
67 };
68 } // namespace Media
69 } // namespace OHOS
70 
71 #endif // OHOS_EVENTHANDLER_H
72