-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest.cpp
More file actions
96 lines (81 loc) · 1.63 KB
/
test.cpp
File metadata and controls
96 lines (81 loc) · 1.63 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
#include "lockfree_queue.h"
#include <string>
#include <stdio.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
struct opUnit {
string name;
int32_t op;
void operator = (const opUnit& v2)
{
name = v2.name;
op = v2.op;
}
};
LFqueue<opUnit> q;
atomic_int producerCount(0);
atomic_int consumerCount(0);
atomic_int endThreadCount(0);
atomic<bool> done (false);
const int iterations = 1000000;
const int producerThreadCount = 4;
const int consumerThreadCount = 4;
void* producer(void *)
{
for (int i = 0; i < iterations; i++) {
opUnit u;
u.op = ++producerCount;
printf("producer:%d\n",u.op);
while (!q.push(u));
}
++endThreadCount;
pthread_exit(0);
}
void* consumer(void *)
{
sleep(1);
opUnit u;
while (!done) {
while (q.pop(u)) {
++consumerCount;
// printf("consumer:%d\n",consumerCount.load());
printf("consumer:%d\n",u.op);
}
}
while (q.pop(u)) {
++consumerCount;
// printf("consumer:%d\n",consumerCount.load());
printf("consumer:%d\n",u.op);
}
++endThreadCount;
pthread_exit(0);
}
int main()
{
if (q.isLockFree()) {
cout << "i am lockfree" << endl;
}
pthread_t tid1, tid2;
for (int i = 0; i != producerThreadCount; ++i) {
int r = pthread_create(&tid1, NULL, producer, NULL);
if (r != 0) {
cout << "create producer:" << r << endl;
}
}
done = true;
for (int i = 0; i != consumerThreadCount; ++i) {
int r = pthread_create(&tid2, NULL, consumer, NULL);
if (r != 0) {
cout << "create consumer:" << r << endl;
}
}
while (1) {
sleep(1);
if (endThreadCount == (producerThreadCount + consumerThreadCount)) {
fflush(stdout);
break;
}
}
return 0;
}