-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_safe_stack.cpp
executable file
·48 lines (41 loc) · 1.14 KB
/
thread_safe_stack.cpp
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
#include <exception>
#include <memory> // for std::shared_ptr<>
#include <mutex>
#include <stack>
struct empty_stack : std::exception{
const char* what() const throw();
};
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);
}
std::shared_ptr<T> pop(){
std::lock_guard<std::mutex> lock(m);
if (data.empty()) throw 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()) throw empty_stack();
value=data.top();
data.pop();
}
bool empty() const{
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
};