spin.cpp
1.17 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
#include "jthread.h"
#include "jspinlock.h"
#include <list>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/syscall.h>
#include <sys/time.h>
#define SPINLOCK
#define LOOPS 10000000
std::list<int> the_list;
#ifdef SPINLOCK
jthread::SpinLock mutex;
#else
jthread::Mutex mutex;
#endif
class Consumer : public jthread::Thread {
private:
public:
Consumer()
{
}
virtual ~Consumer()
{
}
virtual void Run()
{
printf("Consumer TID %lu\n", (unsigned long)syscall( __NR_gettid ));
int i;
while (1) {
mutex.Lock();
if (the_list.empty()) {
mutex.Unlock();
break;
}
i = the_list.front();
the_list.pop_front();
mutex.Unlock();
}
}
};
int main()
{
Consumer consumer1,
consumer2;
struct timeval tv1, tv2;
for (int i = 0; i < LOOPS; i++) {
the_list.push_back(i);
}
gettimeofday(&tv1, NULL);
consumer1.Start();
consumer2.Start();
consumer1.WaitThread();
consumer2.WaitThread();
gettimeofday(&tv2, NULL);
if (tv1.tv_usec > tv2.tv_usec) {
tv2.tv_sec--;
tv2.tv_usec += 1000000;
}
printf("Result: %ld.%ld\n", tv2.tv_sec - tv1.tv_sec, tv2.tv_usec - tv1.tv_usec);
return 0;
}