From 2006b2d212d07cd17cf4b8fc5ec6cfba99dc6168 Mon Sep 17 00:00:00 2001 From: TUNQRT Date: Fri, 7 Mar 2025 10:24:52 +0100 Subject: [PATCH] task assignment --- prod_con.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 prod_con.cpp diff --git a/prod_con.cpp b/prod_con.cpp new file mode 100644 index 0000000..4b664aa --- /dev/null +++ b/prod_con.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +#include + +constexpr unsigned MAX_CONSUME_TIME = 10; +constexpr unsigned MAX_PRODUCE_TIME = 3; + +static char prod_cnt = 'A'; +static int cons_cnt = 0; + +std::mutex os_l; +std::ostream& os = std::cout; + +class Task { +private: + std::chrono::seconds dificulty; +public: + Task() = delete; + Task(const Task&) = delete; + Task(Task&& t) : dificulty(t.dificulty) {} + Task(std::chrono::seconds s) : dificulty(s) {} + void process() { std::this_thread::sleep_for(dificulty); } +}; + +class Producent { +private: + const char id; +public: + Producent() : id(prod_cnt++) { + os << "Producent spawned <" << id << ">" << std::endl; + } + Producent(const Producent&) = delete; + ~Producent() = default; + Task produce() { + std::srand(std::time({})); + std::this_thread::sleep_for(std::chrono::seconds(std::rand() % MAX_PRODUCE_TIME)); + + os_l.lock(); + os << "Task produced <" << id << ">" << std::endl; + os_l.unlock(); + + return Task(std::chrono::seconds(std::rand() % MAX_CONSUME_TIME)); + } +}; + +class Consument { +private: + const int id; +public: + Consument() : id(prod_cnt++) { + os << "Consument spawned <" << id << ">" << std::endl; + } + Consument(const Consument&) = delete; + ~Consument() = default; + void consume(Task&& t) { + t.process(); + + os_l.lock(); + os << "Task processed <" << id << ">" << std::endl; + os_l.unlock(); + } +}; + +//############################################################# + +constexpr unsigned NUM_PRODUCENTS = 1; +constexpr unsigned NUM_CONSUMENTS = 3; \ No newline at end of file