-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.cpp
More file actions
111 lines (94 loc) · 2.66 KB
/
main_test.cpp
File metadata and controls
111 lines (94 loc) · 2.66 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
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
#include <iostream>
#include <future>
#include <exception>
#include <ctime>
#include <sys/time.h>
#include <string>
#include <cassert>
#include <unistd.h>
#include <string.h>
#include "LocklessQueue.hpp"
#include "RegularQueue.hpp"
#include "ShutdownException.hpp"
#define COUNT 10000000
std::atomic<int> x[COUNT];
void clear_x();
void test_queue(Queue<int> &q, std::string q_name);
uint64_t ms_since_epoch();
void enqueue_count(Queue<int>* q);
void dequeue_count(Queue<int>* q);
void verify_x(int);
int main(void) {
std::cout << "Testing queueing and dequeueing of " << COUNT
<< " integers using 4 threads. 2 queueing and 2 dequeueing."
<< std::endl << std::endl;
for(int i = 0; i < 20; i++) {
LocklessQueue<int> lq(2, COUNT/2);
test_queue(lq, "lockless queue");
verify_x(2);
clear_x();
}
for(int i = 0; i < 20; i++) {
RegularQueue<int> rq(COUNT/2);
test_queue(rq, "locking queue");
verify_x(2);
clear_x();
}
}
void test_queue(Queue<int> &q, std::string q_name) {
std::cout << "Starting " << q_name << "." << std::endl;
uint64_t start = ms_since_epoch();
auto put = std::thread(enqueue_count, &q);
auto put2 = std::thread(enqueue_count, &q);
auto get = std::thread(dequeue_count, &q);
auto get2 = std::thread(dequeue_count, &q);
put.join();
put2.join();
get.join();
get2.join();
uint64_t end = ms_since_epoch();
std::cout << "Done. " << q_name << " took: "
<< end - start << "ms." << std::endl;
}
void clear_x() {
memset(&x, 0, COUNT * sizeof(x[0]));
}
void verify_x(int expected) {
std::cout << "Verifying correctness." << std::endl;
bool ok = true;
for(int i = 0; i < COUNT; i++) {
if(x[i] != expected) {
std::cout << "x[" << i << "] == " << x[i] << std::endl;
ok = false;
}
}
if(ok) {
std::cout << "Queue functioned correctly." << std::endl;
}
}
uint64_t ms_since_epoch() {
try {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_usec / 1000) + (tv.tv_sec * 1000);
} catch (ShutdownException e) {}
}
void enqueue_count(Queue<int>* q) {
try {
for(int i = 0; i < COUNT; i++) {
q->enqueue(i);
}
} catch (ShutdownException e) {
std::cout << "enqueue Got shutdown exception." << std::endl;
}
}
void dequeue_count(Queue<int>* q) {
try {
for(int i = 0; i < COUNT; i++) {
int qx = q->dequeue();
x[qx]++;
}
} catch (ShutdownException e) {
std::cout << "dequeue Got shutdown exception." << std::endl;
}
}