-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSemaphore_02.cpp
More file actions
91 lines (69 loc) · 2.41 KB
/
Semaphore_02.cpp
File metadata and controls
91 lines (69 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
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
// ===========================================================================
// Semaphore // Semaphore_02.cpp
// ===========================================================================
#include "../Logger/Logger.h"
#include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <random>
#include <semaphore>
#include <sstream>
#include <thread>
namespace ConcurrencyBinarySemaphore
{
static std::string prefix() {
std::stringstream ss;
ss << "Thread " << std::setw(4) << std::setfill('0') << std::uppercase << std::hex << std::this_thread::get_id() << ": ";
return ss.str();
}
class Document {};
class PrinterQueue
{
private:
std::binary_semaphore m_semaphore;
std::random_device m_device;
std::uniform_int_distribution<size_t> m_distribution;
public:
PrinterQueue() : m_semaphore{ 1 }, m_distribution{ 500, 2000 } {}
public:
void printJob(Document document)
{
m_semaphore.acquire();
size_t duration{ m_distribution(m_device) };
std::string msecs{ std::to_string(duration) };
Logger::log(std::cout, "PrinterQueue: Printing a Job during ", msecs, " millseconds.");
std::this_thread::sleep_for(std::chrono::milliseconds{ duration });
Logger::log(std::cout, "PrinterQueue: The document has been printed");
m_semaphore.release();
}
};
class PrintingJob
{
private:
PrinterQueue& m_printerQueue;
public:
PrintingJob(PrinterQueue& printerQueue) : m_printerQueue{ printerQueue } {}
void operator () () const {
Logger::log(std::cout, "PrintingJob: Going to enqueue a document");
m_printerQueue.printJob(Document{});
}
};
}
void test_binary_semaphore_02()
{
using namespace ConcurrencyBinarySemaphore;
constexpr size_t NumJobs{ 8 };
PrinterQueue printerQueue{};
std::array<std::thread, NumJobs> threads;
for (size_t i{}; i != NumJobs; i++) {
std::thread t{ PrintingJob{ printerQueue } };
threads.at(i) = std::move(t);
}
for (size_t i{}; i != NumJobs; i++) {
threads[i].join();
}
}
// ===========================================================================
// End-of-File
// ===========================================================================