-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockStack.cpp
More file actions
81 lines (74 loc) · 1.71 KB
/
Copy pathLockStack.cpp
File metadata and controls
81 lines (74 loc) · 1.71 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
#include <exception>
#include <stack>
#include <mutex>
#include <stdlib.h>
#include <memory>
#include <stdio.h>
#include <getopt.h>
#include <iostream>
#include <ostream>
#include <chrono>
#include <mutex>
#include <assert.h>
using namespace std;
template<typename T>
class LockStack
{
private:
std::stack<T> data;
pthread_mutex_t mutex;
public:
LockStack(){
pthread_mutex_init(&mutex, NULL);
}
void push(T new_value)
{
pthread_mutex_lock(&mutex);
data.push(std::move(new_value));
pthread_mutex_unlock(&mutex);
}
std::shared_ptr<T> peek()
{
pthread_mutex_lock(&mutex);
if(data.empty()) {
pthread_mutex_unlock(&mutex);
return std::shared_ptr<T>();
}
std::shared_ptr<T> const res(
std::make_shared<T>(data.top()));
pthread_mutex_unlock(&mutex);
return res;
}
std::shared_ptr<T> pop()
{
pthread_mutex_lock(&mutex);
if(data.empty()) {
pthread_mutex_unlock(&mutex);
return std::shared_ptr<T>();
}
std::shared_ptr<T> const res(
std::make_shared<T>(std::move(data.top())));
data.pop();
pthread_mutex_unlock(&mutex);
return res;
}
void pop(T& value)
{
pthread_mutex_lock(&mutex);
if(data.empty()) {
pthread_mutex_unlock(&mutex);
return;
}
value=std::move(data.top());
data.pop();
pthread_mutex_unlock(&mutex);
}
bool empty() const
{
bool res;
pthread_mutex_lock(&mutex);
res = data.empty();
pthread_mutex_unlock(&mutex);
return res;
}
};