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
|
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#define LOCK_TYPE (2) /* 1:mutex; 2:rwlock; 3:atomic */
#if LOCK_TYPE==1
pthread_rwlock_t test_rwlock;
#elif LOCK_TYPE==2
pthread_mutex_t test_mlock;
#elif LOCK_TYPE==3
long atomic_lock = 0;
#endif
unsigned long long g_val;
unsigned long long g_producer_op_times = 0, g_customer_op_times;
static inline void test_lock(long lock_val)
{
#if LOCK_TYPE==1
pthread_rwlock_wrlock(&test_rwlock);
#elif LOCK_TYPE==2
pthread_mutex_lock(&test_mlock);
#elif LOCK_TYPE==3
while((__sync_or_and_fetch(&atomic_lock, lock_val) & 0xF) == lock_val){
;
}
#endif
}
static inline void test_rlock(long lock_val)
{
#if LOCK_TYPE==1
pthread_rwlock_rdlock(&test_rwlock);
#elif LOCK_TYPE==2
pthread_mutex_lock(&test_mlock);
#elif LOCK_TYPE==3
while((__sync_or_and_fetch(&atomic_lock, lock_val) & 0xF) == lock_val){
;
}
#endif
}
static inline void test_unlock(long lock_mask)
{
#if LOCK_TYPE==1
pthread_rwlock_unlock(&test_rwlock);
#elif LOCK_TYPE==2
pthread_mutex_unlock(&test_mlock);
#elif LOCK_TYPE==3
__sync_and_and_fetch(&atomic_lock, lock_mask);
#endif
}
/*
���bit: producer;
��2bit : customer;
*/
static void *producer_thread(void *arg)
{
int i;
//for(i = 0; i < 9999999; i++){
while(1){
test_lock(0x01);
g_val++;
test_unlock(0xFE);
g_producer_op_times++;
}
return NULL;
}
static void *customer_thread(void *arg)
{
unsigned long long tmp;
int i;
//for(i = 0; i < 9999999; i++){
while(1){
test_rlock(0x02);
tmp = g_val;
test_unlock(0xFD);
g_customer_op_times++;
}
return NULL;
}
static void *stat_thread(void *arg)
{
unsigned long long last_op_times = 0;
while(1){
printf("op PPS: %llu\n", g_customer_op_times + g_producer_op_times - last_op_times);
last_op_times = g_customer_op_times + g_producer_op_times;
sleep(1);
}
return NULL;
}
int main(void)
{
#if LOCK_TYPE==1
pthread_rwlock_init(&test_rwlock, NULL);
#elif LOCK_TYPE==2
pthread_mutex_init(&test_mlock, NULL);
#endif
pthread_t stat_pid, producer_pid, customer_pid;
pthread_create(&stat_pid, NULL, stat_thread, NULL);
pthread_create(&producer_pid, NULL, producer_thread, NULL);
pthread_create(&customer_pid, NULL, customer_thread, NULL);
pthread_join(producer_pid, NULL);
pthread_join(customer_pid, NULL);
printf("%llu\n", g_val);
return 0;
}
|