-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc79_concurrent_queue.cpp
More file actions
96 lines (82 loc) · 1.94 KB
/
c79_concurrent_queue.cpp
File metadata and controls
96 lines (82 loc) · 1.94 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
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <future>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
/*!
* \brief An concurrent queue implementation
*/
namespace concurrency
{
class ConcurrentQueueException : public std::runtime_error
{
public:
ConcurrentQueueException() : std::runtime_error("Empty queue") { }
ConcurrentQueueException(const char* s) : std::runtime_error(s) { }
};
template<typename T>
class ConcurrentQueue
{
public:
ConcurrentQueue() = default;
~ConcurrentQueue() = default;
void push(T value)
{
std::unique_lock<std::mutex> lock{_m};
_data.push(value);
lock.unlock();
_cond.notify_one();
}
void pop(T& value)
{
std::unique_lock<std::mutex> lock{_m};
// if read before write, an exception will be thrown,
// if (_data.empty())
// {
// throw ConcurrentQueueException();
// }
// or better wait until the queue has elements again
_cond.wait(lock, [this](){ return !_data.empty(); });
value = _data.front();
_data.pop();
}
private:
std::queue<T> _data;
std::mutex _m;
std::condition_variable _cond;
};
}
concurrency::ConcurrentQueue<std::string> queue;
void reader()
{
std::cout << "Reading queue..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::string data;
try
{
queue.pop(data);
std::cout << "Read data: '" << data << "'\n";
}
catch(const std::exception& e)
{
std::cerr << "Error: " << e.what() << '\n';
}
}
void writer()
{
std::cout << "Writing queue..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
queue.push("some data");
}
int main()
{
auto w = std::async(std::launch::async, writer);
auto r = std::async(std::launch::async, reader);
w.wait();
r.wait();
return 0;
}