1 /*
2  * Copyright (c) 2023 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 #ifndef MESSAGE_QUEUE_H
16 #define MESSAGE_QUEUE_H
17 
18 #include <queue>
19 #include <memory>
20 #include <string>
21 #include <pthread.h>
22 #include <mutex>
23 #include <condition_variable>
24 #include "nocopyable.h"
25 
26 namespace OHOS {
27 namespace IntellVoiceUtils {
28 struct SynInfo {
29     std::mutex mutex_;
30     std::condition_variable cv_;
31 };
32 struct Message {
33 public:
34     explicit Message(uint32_t what);
35     Message(uint32_t what, int32_t arg1);
36     Message(uint32_t what, int32_t arg1, int32_t arg2, float arg3);
37     Message(uint32_t what, int32_t arg1, int32_t arg2, const std::string &obj);
38     Message(uint32_t what, int32_t arg1, int32_t arg2, float arg3, const std::string &obj);
39     Message(uint32_t what, std::shared_ptr<void> obj2);
40     Message(uint32_t what, std::shared_ptr<void> obj2, std::shared_ptr<void> obj3);
41     Message(uint32_t what, void* voidPtr);
42     Message(uint32_t what, int32_t arg1, void* voidPtr);
43     ~Message();
44 
45     uint32_t what_ = 0;
46     int32_t arg1_ = 0;
47     int32_t arg2_ = 0;
48     float arg3_ = 0.0f;
49     std::string obj_;
50     std::shared_ptr<void> obj2_ = nullptr;
51     std::shared_ptr<void> obj3_ = nullptr;
52     void *voidPtr_ = nullptr;
53     uint32_t callbackId_ = 0;
54 
55     std::shared_ptr<SynInfo> result_ = nullptr;
56 };
57 
58 class MessageQueue {
59 public:
60     explicit MessageQueue(uint32_t size);
61     ~MessageQueue();
62     std::shared_ptr<Message> ReceiveMsg();
63     bool SendMsg(std::shared_ptr<Message> msg);
64     void Clear();
65 
66 private:
67     uint32_t size_;
68     pthread_mutex_t lock_;
69     pthread_cond_t cond_;
70     std::queue<std::shared_ptr<Message>> queue_;
71     DISALLOW_COPY(MessageQueue);
72     DISALLOW_MOVE(MessageQueue);
73 };
74 }
75 }
76 #endif
77