Advertisement
Guest User

Untitled

a guest
Oct 28th, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include <chrono>
  2. #include <condition_variable>
  3. #include <iomanip>
  4. #include <iostream>
  5. #include <mutex>
  6. #include <queue>
  7. #include <sstream>
  8. #include <thread>
  9. #include <vector>
  10.  
  11. using namespace std;
  12. using namespace chrono_literals;
  13.  
  14. struct pcout : public stringstream {
  15.     static inline mutex cout_mutex;
  16.     ~pcout() {
  17.         lock_guard<mutex> l{cout_mutex};
  18.         cout << rdbuf();
  19.     }
  20. };
  21.  
  22. queue<size_t> q;
  23. mutex g_mutex;
  24. bool production_stopped{false};
  25.  
  26. condition_variable go_produce;
  27. condition_variable go_consume;
  28.  
  29. static void producer(size_t id, size_t items, size_t stock) {
  30.     for (size_t i = 0; i < items; ++i) {
  31.         unique_lock<mutex> lock(g_mutex);
  32.         go_produce.wait(lock, [&] { return q.size() < stock; });
  33.         q.push(id * 100 + i);
  34.         pcout{} << "   Producer " << id << " --> item " << setw(3) << q.back() << '\n';
  35.         go_consume.notify_all();
  36.         this_thread::sleep_for(100ms);
  37.     }
  38.     pcout{} << "EXIT: Producer " << id << '\n';
  39. }
  40.  
  41. static void consumer(size_t id) {
  42.     while (!production_stopped || !q.empty()) {
  43.         unique_lock<mutex> lock(g_mutex);
  44.         if (go_consume.wait_for(lock, 1s,
  45.                                 [] { return !q.empty(); })) {
  46.             pcout{} << "item "
  47.                     << setw(3) << q.front()
  48.                     << " --> Consumer "
  49.                     << id << '\n';
  50.             q.pop();
  51.             go_produce.notify_all();
  52.             this_thread::sleep_for(200ms);
  53.         }
  54.     }
  55.     pcout{} << "EXIT: Producer " << id << '\n';
  56. }
  57.  
  58. int main() {
  59.     vector<thread> workers;
  60.     vector<thread> consumers;
  61.     for (size_t i = 0; i < 3; ++i) {
  62.         workers.emplace_back(producer, i, 15, 5);
  63.     }
  64.     for (size_t i = 0; i < 5; ++i) {
  65.         consumers.emplace_back(consumer, i);
  66.     }
  67.     for (auto& t : workers) {
  68.         t.join();
  69.     }
  70.     production_stopped = true;
  71.     for (auto& t : consumers) {
  72.         t.join();
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement