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 ANBOX_COMMON_MESSAGE_CHANNEL_H
16 #define ANBOX_COMMON_MESSAGE_CHANNEL_H
20 #include <condition_variable>
26 // Base non-templated class used to reduce the amount of template
28 class MessageChannelBase {
30 // Constructor. |capacity| is the buffer capacity in messages.
31 MessageChannelBase(size_t capacity);
34 ~MessageChannelBase();
37 // Call this method in the sender thread before writing a new message.
38 // This returns the position of the available slot in the message array
39 // where to copy the new fixed-size message. After the copy, call
41 size_t before_write();
43 // To be called after beforeWrite() and copying a new fixed-size message
44 // into the array. This signal the receiver thread that there is a new
48 // Call this method in the receiver thread before reading a new message.
49 // This returns the position in the message array where the new message
50 // can be read. Caller must process the message, then call afterRead().
53 // To be called in the receiver thread after beforeRead() and processing
54 // the corresponding message.
62 std::condition_variable can_read_;
63 std::condition_variable can_write_;
66 // Helper class used to implement an uni-directional IPC channel between
67 // two threads. The channel can be used to send fixed-size messages of type
68 // |T|, with an internal buffer size of |CAPACITY| items. All calls are
71 // Usage is pretty straightforward:
73 // - From the sender thread, call send(msg);
74 // - From the receiver thread, call receive(&msg);
76 template <typename T, size_t CAPACITY>
77 class MessageChannel : public MessageChannelBase {
79 MessageChannel() : MessageChannelBase(CAPACITY) {}
81 void send(const T& msg) {
82 size_t pos = before_write();
87 void receive(T* msg) {
88 size_t pos = before_read();