From b54ee7dd95285175443e5dbb95f45f72d5976f62 Mon Sep 17 00:00:00 2001 From: Robin Mueller Date: Wed, 5 Oct 2022 11:59:32 +0200 Subject: [PATCH] add 02 main IPC --- main-02.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ ws-ipc/README.md | 2 ++ 2 files changed, 50 insertions(+) create mode 100644 main-02.cpp diff --git a/main-02.cpp b/main-02.cpp new file mode 100644 index 0000000..d50a078 --- /dev/null +++ b/main-02.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +using namespace std; + +std::mutex QUEUE_MUTEX; +std::queue INT_QUEUE; + +static uint32_t SENT_INTS = 0; + +void intSender() { + using namespace std::chrono_literals; + while(true) { + QUEUE_MUTEX.lock(); + INT_QUEUE.push(++SENT_INTS); + QUEUE_MUTEX.unlock(); + cout << "intSender: Sent value " << SENT_INTS << endl; + this_thread::sleep_for(1000ms); + } +} + +void intReceiver() { + using namespace std::chrono_literals; + while(true) { + std::optional optInt; + QUEUE_MUTEX.lock(); + if(not INT_QUEUE.empty()) { + optInt = INT_QUEUE.back(); + INT_QUEUE.pop(); + } + QUEUE_MUTEX.unlock(); + if (optInt.has_value()) { + cout << "intReceiver: Received integer value " << + optInt.value() << endl; + } + this_thread::sleep_for(800ms); + } +} +int main() { + cout << "Hello World" << endl; + std::thread t0(intSender); + std::thread t1(intReceiver); + t0.join(); + t1.join(); +} diff --git a/ws-ipc/README.md b/ws-ipc/README.md index 6ccf759..8e4991d 100644 --- a/ws-ipc/README.md +++ b/ws-ipc/README.md @@ -29,3 +29,5 @@ if you are completely new to concurrency in C++. C++ does not really have an built-in message queue implementation. We are going to use a `std::queue` in conjunction with a `std::mutex` to have something similar to a message queue API. + +## \ No newline at end of file