add 02 main IPC
This commit is contained in:
parent
a839c7dc3e
commit
b54ee7dd95
48
main-02.cpp
Normal file
48
main-02.cpp
Normal 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();
|
||||||
|
}
|
@ -29,3 +29,5 @@ if you are completely new to concurrency in C++.
|
|||||||
C++ does not really have an built-in message queue implementation.
|
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
|
We are going to use a `std::queue` in conjunction with a `std::mutex` to
|
||||||
have something similar to a message queue API.
|
have something similar to a message queue API.
|
||||||
|
|
||||||
|
##
|
Loading…
Reference in New Issue
Block a user