-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue_test.cpp
140 lines (118 loc) · 2.37 KB
/
queue_test.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include "queue.hpp"
#include <stdio.h>
#include "thread_pool.hpp"
#include <stdlib.h>
#include <queue>
using namespace lockfree;;
queue<int> lfqueue;
/*
int main(void){
lfqueue.enq(new item(1,2,3));
lfqueue.deq();
return 0;
}
/*/
std::queue<int> g_stlqueue;
#define MAX 20000000
#define CORE 4
void enque(int offset){
for(int i=0 ;i<MAX/CORE; i++){
lfqueue.enq(i+offset);
}
}
void deque(int){
for(int i = 0;i<MAX/CORE;i++){
lfqueue.deq();
}
}
class mutex{
private:
mutex(void);
mutex(const mutex&);
private:
pthread_mutex_t *target;
public:
mutex(pthread_mutex_t* _target):target(_target){
lock();
}
~mutex(){
unlock();
}
inline void lock(void){
pthread_mutex_lock(target);
}
inline void unlock(void){
pthread_mutex_unlock(target);
}
};
pthread_mutex_t enq_mutex;
pthread_mutex_t deq_mutex;
void enque_mutex(int i){
for(int i = 0;i<MAX/CORE;i++){
mutex lock(&enq_mutex);
g_stlqueue.push(i);
}
}
void deque_mutex(int){
for(int i = 0;i<MAX/CORE;i++){
mutex lock(&deq_mutex);
int dequed;
do{
dequed = g_stlqueue.front();
}while(dequed == 0);
g_stlqueue.pop();
}
}
//#define TEST
#include "gettime.h"
pthread_mutex_t printmutex;
int main (void)
{
// random seed
srand((unsigned int)time(NULL));
double enquestart,enqueend,dequestart,dequeend;
threadpool<int> threads(20);
printf("%d thread initialized, %d items \n",20, MAX);
printf("lockfree\t|");
// lockfree queue start
enquestart = gettime();
//*
for(int i = 0; i < CORE; i++){
threads.run(enque,i*MAX/CORE);
}
threads.wait();
enqueend = gettime();
printf(" enque: %lf ", enqueend - enquestart);
dequestart = gettime();
for(int i = 0; i < CORE; i++){
threads.run(deque,0);
}
threads.wait();
dequeend = gettime();
printf(" deque: %lf\n", dequeend - dequestart);
// mutex with stl start
pthread_mutex_init(&printmutex,0);
pthread_mutex_init(&enq_mutex,0);
pthread_mutex_init(&deq_mutex,0);
printf("STL(mutex)\t|");
enquestart = gettime();
//*
for(int i = 0; i < MAX/CORE; i++){
threads.run(enque_mutex,i*MAX/CORE);
}
/*/
for(int i = 1; i <= MAX; i++){
g_stlqueue.push(i);
}
//*/
enqueend = gettime();
printf(" enque: %lf ", enqueend - enquestart);
dequestart = gettime();
for(int i = 0; i < MAX/CORE; i++){
threads.run(deque_mutex,0);
}
threads.wait();
dequeend = gettime();
printf(" deque: %lf\n", dequeend - dequestart);
}
//*/