-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy paththreadsafe_stack.cpp
More file actions
68 lines (59 loc) · 1.57 KB
/
Copy paththreadsafe_stack.cpp
File metadata and controls
68 lines (59 loc) · 1.57 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
//
// Created by yryang on 2021/10/19.
//
#include "threadsafe_stack.h"
#include <iostream>
#include <vector>
#include "util.h"
namespace threadsafe_stack{
void push_test(threadsafe_stack<int> &stack, std::vector<int> v){
for (auto &&vv: v){
stack.push(vv);
}
v.clear();
while (!stack.empty()){
try {
int t;
if(stack.pop(t)){
v.push_back(t);
}
} catch (...) {
std::cout << "wrong empty\n"; // stack.empty() stack.pop() 有并发冲突
}
}
for (auto &&vv: v){
stack.push(vv);
}
}
void test(){
threadsafe_stack<int> stack;
int N = 1000;
int thread_num = 10;
std::vector<std::thread> threads;
for (int i = 0; i < thread_num; ++i) {
std::vector<int> v;
for (int j = 0; j < N/thread_num; ++j) {
v.push_back(j + (N/thread_num)*i);
}
threads.emplace_back(push_test, std::ref(stack), v);
}
for (int i = 0; i < thread_num; ++i) {
threads[i].join();
}
std::vector<int> res;
while (!stack.empty()){
int t;
stack.pop(t);
res.push_back(t);
}
std::sort(res.begin(), res.end());
for (int i = 0; i < N; ++i) {
ASSERT(res[i] == i, "thread safe stack: wrong" );
}
std::cout << "test success\n";
}
}
int main(){
threadsafe_stack::test();
return 0;
}