add 02 main IPC

This commit is contained in:
Robin Müller 2022-10-05 11:59:32 +02:00
parent a839c7dc3e
commit b54ee7dd95
No known key found for this signature in database
GPG Key ID: 11D4952C8CCEF814
2 changed files with 50 additions and 0 deletions

48
main-02.cpp Normal file
View File

@ -0,0 +1,48 @@
#include <iostream>
#include <queue>
#include <mutex>
#include <thread>
#include <optional>
using namespace std;
std::mutex QUEUE_MUTEX;
std::queue<int> 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<int> 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();
}

View File

@ -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.
##