-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbirthdayPresents_v1.cpp
More file actions
123 lines (97 loc) · 2.5 KB
/
birthdayPresents_v1.cpp
File metadata and controls
123 lines (97 loc) · 2.5 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <unistd.h>
#include <atomic>
#include <memory>
#include <thread>
#include <random>
#include <chrono>
#include <random>
#include <functional>
#define PRESENTS 500000
// Linked list implementation from C++ Concurrency in Action
template<typename T>
class queue
{
private:
struct node
{
T data;
std::unique_ptr<node> next;
node(T data_):
data(std::move(data_))
{}
};
std::unique_ptr<node> head;
node* tail;
public:
queue(): tail(nullptr)
{}
queue(const queue& other)=delete;
queue& operator=(const queue& other)=delete;
std::shared_ptr<T> try_pop()
{
if(!head)
{
return std::shared_ptr<T>();
}
std::shared_ptr<T> const res(std::make_shared<T>(std::move(head->data)));
std::unique_ptr<node> const old_head = std::move(head);
head = std::move(old_head->next);
if(!head)
tail = nullptr;
return res;
}
void push(T new_value)
{
std::unique_ptr<node> p(new node(std::move(new_value)));
node* const new_tail=p.get();
if(tail)
{
tail->next=std::move(p);
}
else
{
head=std::move(p);
}
tail=new_tail;
}
};
// Minotaur random selection
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0, PRESENTS - 1);
auto randomPresent = std::bind ( distribution, generator);
// Set the starting value of the presents
std::atomic<int> presents(PRESENTS);
// Birthday handling function
void presentHandler()
{
queue<int> ll;
// while their are presents left
while(presents){
if(rand() % 2 && presents != 0)
{
ll.push(randomPresent());
//std::cout << "Pushed " << i << '\n';
presents--;
}
else if (ll.try_pop())
{
//write the thank you letter
}
std::cout << "Presents = " << presents;
//std::this_thread::sleep_for (std::chrono::seconds(1));
}
// Escaped
}
int main()
{
std::thread servants[8];
for (int i=0; i<10; i+=2)
{
servants[i] = std::thread(presentHandler);
}
for (auto& s : servants) {
s.join();
}
return 0;
}