- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <queue>
std::condition_variable messages_cv;
std::mutex messages_mtx;
std::queue<std::string> messages;
std::atomic_bool running = true; // TODO: stop_token when c++20
void pull_messages_thread() {
bool should_run = running;
while (should_run) {
std::unique_lock lock(messages_mtx);
messages_cv.wait(lock, []{ return !messages.empty() || !running; });
if (messages.empty()) return;
auto message = std::move(messages.front());
messages.pop();
should_run = running || !messages.empty();
lock.unlock();
std::cout << "Processing\t" + message + "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(20));
std::cout << "Processed\t" + message + "\n";
}
}
int main() {
std::thread puller(pull_messages_thread);
for (std::size_t i = 0; i < 10; ++i) {
std::string message = "Message<" + std::to_string(i) + ">";
std::unique_lock lock(messages_mtx);
std::cout << "Storing \t" + message + "\n";
messages.emplace(std::move(message));
lock.unlock();
messages_cv.notify_all();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
running = false;
messages_cv.notify_all();
puller.join();
}
/*
Storing Message<0>
Processing Message<0>
Storing Message<1>
Storing Message<2>
Processed Message<0>
Processing Message<1>
Storing Message<3>
Processed Message<1>
Processing Message<2>
Storing Message<4>
Storing Message<5>
Processed Message<2>
Processing Message<3>
Storing Message<6>
Storing Message<7>
Processed Message<3>
Processing Message<4>
Storing Message<8>
Storing Message<9>
Processed Message<4>
Processing Message<5>
Processed Message<5>
Processing Message<6>
Processed Message<6>
Processing Message<7>
Processed Message<7>
Processing Message<8>
Processed Message<8>
Processing Message<9>
Processed Message<9>
*/
Комментарии (0) RSS
Добавить комментарий