-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path240 A Thread Pool.cpp
More file actions
104 lines (81 loc) · 1.88 KB
/
Copy path240 A Thread Pool.cpp
File metadata and controls
104 lines (81 loc) · 1.88 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
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
#include <vector>
#include <mutex>
#include <cmath>
#include <queue>
using namespace std;
mutex g_mtx;
template <typename E>
class blocking_queue
{
private:
mutex _mtx;
condition_variable _cond;
int _max_size;
queue<E> _queue;
public:
blocking_queue(int max_size) : _max_size(max_size)
{
}
void push(E e)
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this]() { return _queue.size() < _max_size; });
_queue.push(e);
lock.unlock();
_cond.notify_one();
}
E front()
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this]() { return !_queue.empty(); });
return _queue.front();
}
void pop()
{
unique_lock<mutex> lock(_mtx);
_cond.wait(lock, [this]() { return !_queue.empty(); });
_queue.pop();
lock.unlock();
_cond.notify_one();
}
int size()
{
lock_guard<mutex> lock(_mtx);
return _queue.size();
}
};
int work(int id)
{
unique_lock<mutex> lock(g_mtx);
cout << "Starting " << id << endl;
lock.unlock();
int seconds = int((5.0 * rand()) / RAND_MAX + 3);
this_thread::sleep_for(chrono::seconds(seconds));
return id;
}
int main()
{
// Here the argument supplied to the queue needs to be
// one less than the number of threads you want to launch.
blocking_queue<shared_future<int>> futures(2);
thread t([&]() {
for (int i = 0; i < 20; i++)
{
shared_future<int> f = async(launch::async, work, i);
futures.push(f);
}
});
for (int i = 0; i < 20; i++)
{
shared_future<int> f = futures.front();
int value = f.get();
futures.pop();
cout << "Returned: " << value << endl;
}
t.join();
return 0;
}