task assignment
This commit is contained in:
commit
2006b2d212
|
@ -0,0 +1,70 @@
|
|||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
|
||||
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;
|
Loading…
Reference in New Issue