-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread4.c
123 lines (97 loc) · 2.71 KB
/
thread4.c
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
/**
* @brief
*
* @author jervis
* @time 11/06/10 08:45:10
* @version 0.1
*
* Copyright (C) jervis <[email protected]>
*
*/
#include "jlib.h"
#define ORANGE_MAX_VALUE 1000000
#define APPLE_MAX_VALUE 100000000
#define MSECOND 1000000
typedef struct {
unsigned long long a;
unsigned long long b;
pthread_rwlock_t rwlock;
} apple;
typedef struct {
int a[ORANGE_MAX_VALUE];
int b[ORANGE_MAX_VALUE];
} orange;
void *addx(void *arg)
{
unsigned long long sum=0;
struct timeval tpstart,tpend;
float timeuse;
apple *app = arg;
gettimeofday(&tpstart, NULL);
Pthread_rwlock_wrlock(&app->rwlock);
for(sum=0;sum<=APPLE_MAX_VALUE/2;sum++)
{
app->a += sum;
app->b += sum;
}
Pthread_rwlock_unlock(&app->rwlock);
gettimeofday(&tpend, NULL);
timeuse=MSECOND*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=MSECOND;
printf("addx thread:%#lx,Used Time:%f\n",pthread_self(),timeuse);
return NULL;
}
void *addy(void *arg)
{
unsigned long long sum=0;
struct timeval tpstart,tpend;
float timeuse;
apple *app = arg;
gettimeofday(&tpstart, NULL);
Pthread_rwlock_wrlock(&app->rwlock);
for(sum=APPLE_MAX_VALUE/2 + 1;sum<APPLE_MAX_VALUE;sum++)
{
app->a += sum;
app->b += sum;
}
Pthread_rwlock_unlock(&app->rwlock);
gettimeofday(&tpend, NULL);
timeuse=MSECOND*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=MSECOND;
printf("addy thread:%#lx,Used Time:%f\n",pthread_self(),timeuse);
return NULL;
}
int main(int argc, char* argv[])
{
int i;
apple test;
orange test1 = { {0}, {0} };
unsigned long long sum=APPLE_MAX_VALUE,index=0;
struct timeval tpstart,tpend;
float timeuse;
pthread_attr_t attr;
pthread_t tid[2];
test.a = 0;
test.b = 0;
/* get start time */
gettimeofday(&tpstart, NULL);
/* For portability, explicitly create threads in a joinable state */
Pthread_attr_init(&attr);
Pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
Pthread_rwlock_init(&test.rwlock, NULL);
Pthread_create(&tid[0], &attr, addx, &test);
Pthread_create(&tid[1], &attr, addy, &test);
for(index=0;index<ORANGE_MAX_VALUE;index++)
{
sum += +test1.a[index]+test1.b[index];
}
for (i = 0; i < 2; i++)
Pthread_join(tid[i], NULL);
Pthread_rwlock_destroy(&test.rwlock);
gettimeofday(&tpend, NULL);
timeuse=MSECOND*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=MSECOND;
printf("main thread:%#lx,Used Time:%f\n",pthread_self(),timeuse);
printf("a = %llu\nb = %llu\nsum = %llu\n",test.a,test.b,sum);
return 0;
}