605190a04e8fc2d49e8fead5abd7e463e25ce0bb
[platform/core/api/mediavision.git] / mv_machine_learning / common / include / async_manager.h
1 /**
2  * Copyright (c) 2023 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 #ifndef __ASYNC_MANAGER_H__
18 #define __ASYNC_MANAGER_H__
19
20 #include <queue>
21 #include <thread>
22 #include <mutex>
23 #include <condition_variable>
24 #include <atomic>
25 #include <functional>
26
27 #include <mv_common.h>
28 #include <mv_inference_type.h>
29
30 namespace mediavision
31 {
32 namespace machine_learning
33 {
34 template<typename T> struct AsyncInputQueue {
35         unsigned long frame_number {};
36         std::vector<std::vector<T> > inputs;
37 };
38
39 template<typename R> class AsyncManager
40 {
41 private:
42         using CallbackType = std::function<void()>;
43
44         std::queue<AsyncInputQueue<unsigned char> > _incoming_queue;
45         std::queue<R> _outgoing_queue;
46         std::mutex _incoming_queue_mutex;
47         std::mutex _outgoing_queue_mutex;
48         std::unique_ptr<std::thread> _thread_handle;
49         std::atomic<bool> _exit_thread { false };
50         std::condition_variable _outgoing_queue_event;
51         std::condition_variable _incoming_queue_event;
52         unsigned long _input_frame_number {};
53         CallbackType _callback;
54
55         template<typename T> void pushToInput(AsyncInputQueue<T> &inputQueue);
56         template<typename T> bool isInputQueueEmpty();
57         void waitforInputQueue();
58         R popFromOutput();
59         bool isOutputQueueEmpty();
60         void waitforOutputQueue();
61         template<typename T> void inferenceThreadLoop();
62         template<typename T> void invoke();
63
64 public:
65         AsyncManager(const CallbackType &cb);
66         virtual ~AsyncManager() = default;
67
68         bool isWorking();
69         void stop();
70         template<typename T> AsyncInputQueue<T> popFromInput();
71         void pushToOutput(R &output);
72         template<typename T> void push(std::vector<std::vector<T> > &inputs);
73         R pop();
74 };
75
76 } // machine_learning
77 } // mediavision
78
79 #endif