Thread-safe container for sharing data between threads (synchronized queue). Header-only. Compatible with C++11.
- Thread-safe push and fetch.
- Use stream operators to push (<<) and fetch (>>) items.
- Value type must be default constructible.
- Blocking (forever waiting to fetch).
- Range-based for loop supported.
- Close to prevent pushing and stop waiting to fetch.
- Integrates with some of the STD algorithms. Eg:
std::move(ch.begin(), ch.end(), ...)
std::transform(input_chan.begin(), input_chan.end(), msd::back_inserter(output_chan))
.std::copy_if(chan.begin(), chan.end(), ...);
- Tested with GCC, Clang, and MSVC.
- Includes stack-based, exception-free alternative (static channel).
- C++11 or newer
Choose one of the methods:
- Copy the include directory into your project and add it to your include path.
- CMake FetchContent
- CMake install - Choose a version, then run:
VERSION=X.Y.Z \
&& wget https://github.com/andreiavrammsd/cpp-channel/archive/refs/tags/v$VERSION.zip \
&& unzip v$VERSION.zip \
&& cd cpp-channel-$VERSION \
&& mkdir build && cd build \
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local \
&& sudo cmake --install .
#include <cassert>
#include <msd/channel.hpp>
int main() {
msd::channel<int> chan; // unbuffered
int in = 1;
int out = 0;
// Send to channel
chan << in;
// Read from channel
chan >> out;
assert(out == 1);
}
#include <msd/channel.hpp>
int main() {
msd::channel<int> chan{2}; // buffered
// Send to channel
chan << 1;
chan << 2;
chan << 3; // blocking because capacity is 2 (and no one reads from channel)
}
#include <msd/channel.hpp>
int main() {
msd::channel<int> chan{2}; // buffered
int in = 1;
int out = 0;
// Send to channel
chan << in;
chan << in;
// Read from channel
chan >> out;
chan >> out;
chan >> out; // blocking because channel is empty (and no one writes on it)
}
#include <iostream>
#include <msd/channel.hpp>
int main() {
msd::channel<int> chan;
int in1 = 1;
int in2 = 2;
chan << in1 << in2;
for (const auto out : chan) { // blocking: forever waiting for channel items
std::cout << out << '\n';
}
}
#include <msd/static_channel.hpp>
int main() {
msd::static_channel<int, 2> chan{}; // always buffered
int in = 1;
int out = 0;
// Send to channel
chan.write(in);
chan.write(in);
// Read from channel
chan.read(out);
chan.read(out);
chan.read(out); // blocking because channel is empty (and no one writes on it)
}
See examples and documentation.
- In some cases, the integration with some STD algorithms does not compile with MSVC. See the Transform test.
Developed with CLion and Visual Studio Code.