-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_fine.cpp
69 lines (62 loc) · 1.37 KB
/
list_fine.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdexcept>
#include "benchmark.hpp"
struct node {
spinlock lock;
data val;
node *next;
};
class List {
public:
node *head;
List() {
head = new node;
head->next = nullptr;
}
~List() {
while (head != nullptr) {
node *next = head->next;
delete head;
head = next;
}
}
void push(data item) {
node *newitem = new node;
newitem->val = item;
head->lock.lock();
newitem->next = head->next;
head->next = newitem;
head->lock.unlock();
}
data pop() {
head->lock.lock();
if (head->next == nullptr) {
head->lock.unlock();
throw std::runtime_error("Can't pop from an empty list");
}
node *oldhead = head->next;
oldhead->lock.lock();
data ret = oldhead->val;
head->next = oldhead->next;
delete oldhead;
head->lock.unlock();
return ret;
}
data sum() {
data s = 0;
head->lock.lock();
node *cur = head;
while (cur->next != nullptr) {
node *next = cur->next;
next->lock.lock();
s += next->val;
cur->lock.unlock();
cur = next;
}
cur->lock.unlock();
return s;
}
};
int main() {
List l;
benchmark_list(l);
}