1 // Copyright 2014 The Android Open Source Project
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #ifndef EMUGL_COMMON_MESSAGE_CHANNEL_H
16 #define EMUGL_COMMON_MESSAGE_CHANNEL_H
18 #include "emugl/common/condition_variable.h"
19 #include "emugl/common/mutex.h"
25 // Base non-templated class used to reduce the amount of template
27 class MessageChannelBase {
29 // Constructor. |capacity| is the buffer capacity in messages.
30 MessageChannelBase(size_t capacity);
33 ~MessageChannelBase();
36 // Call this method in the sender thread before writing a new message.
37 // This returns the position of the available slot in the message array
38 // where to copy the new fixed-size message. After the copy, call
42 // To be called after beforeWrite() and copying a new fixed-size message
43 // into the array. This signal the receiver thread that there is a new
47 // Call this method in the receiver thread before reading a new message.
48 // This returns the position in the message array where the new message
49 // can be read. Caller must process the message, then call afterRead().
52 // To be called in the receiver thread after beforeRead() and processing
53 // the corresponding message.
61 ConditionVariable mCanRead;
62 ConditionVariable mCanWrite;
65 // Helper class used to implement an uni-directional IPC channel between
66 // two threads. The channel can be used to send fixed-size messages of type
67 // |T|, with an internal buffer size of |CAPACITY| items. All calls are
70 // Usage is pretty straightforward:
72 // - From the sender thread, call send(msg);
73 // - From the receiver thread, call receive(&msg);
75 template <typename T, size_t CAPACITY>
76 class MessageChannel : public MessageChannelBase {
78 MessageChannel() : MessageChannelBase(CAPACITY) {}
80 void send(const T& msg) {
81 size_t pos = beforeWrite();
86 void receive(T* msg) {
87 size_t pos = beforeRead();
98 #endif // EMUGL_COMMON_MESSAGE_CHANNEL_H