andreiavrammsd / cpp-channel

Thread-safe container for sharing data between threads
https://blog.andreiavram.ro/cpp-channel-thread-safe-container-share-data-threads/
MIT License
400 stars 28 forks source link
channel concurrent-queue cpp multithreading queue synchronized-queue thread-safe thread-safe-queue

Channel

build

codecov

Thread-safe container for sharing data between threads. Header-only.

Requirements

Installation

Copy the include directory to your project and add it to your include path. Or see CMakeLists.txt from the CMake project example .

Usage

#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';
    }
}

See examples.


Developed with CLion

JetBrains