-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadSafeStack.cc
More file actions
61 lines (54 loc) · 1.38 KB
/
Copy pathThreadSafeStack.cc
File metadata and controls
61 lines (54 loc) · 1.38 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
// This is part of some learnings from Concurrency book.
#include <stack>
#include <mutex>
#include <memory>
#include <iostream>
using namespace std;
template<typename T>
class threadsafe_stack
{
private:
std::stack<T> data;
mutable std::mutex m;
public:
threadsafe_stack(){}
threadsafe_stack(const threadsafe_stack& other)
{
std::lock_guard<std::mutex> lock(other.m);
data=other.data;
}
threadsafe_stack& operator=(const threadsafe_stack&) = delete;
void push(T new_value)
{
std::lock_guard<std::mutex> lock(m);
data.push(new_value);
}
// TODO: normally we dont prefer to use exceptions in production code, so what is the ideal way
// of informing to client when the stack is empty?
// 1) maybe return a nullptr here?
std::shared_ptr<T> pop()
{
std::lock_guard<std::mutex> lock(m);
if(data.empty())
cout << "You are accessing an empty stack.";
std::shared_ptr<T> const res(std::make_shared<T>(data.top()));
data.pop();
return res;
}
void pop(T& value)
{
std::lock_guard<std::mutex> lock(m);
if(data.empty())
cout << "You are accessing an empty stack.";
value=data.top();
data.pop();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
};
int main()
{
}