This repository has been archived by the owner on Feb 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathmutex.c
92 lines (81 loc) · 2.16 KB
/
mutex.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
/********************************************************
* An example source module to accompany...
*
* "Using POSIX Threads: Programming with Pthreads"
* by Brad nichols, Dick Buttlar, Jackie Farrell
* O'Reilly & Associates, Inc.
* Modified by A.Kostin
********************************************************
* mutex.c
*
* Simple multi-threaded example with a mutex lock.
*/
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int);
int common = 0; /* A shared variable for two threads */
int r1 = 0, r2 = 0, r3 = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int main() {
pthread_t thread1, thread2;
if (pthread_create(&thread1, NULL, (void *)do_one_thing,
(void *)&common) != 0) {
perror("pthread_create");
exit(1);
}
if (pthread_create(&thread2, NULL, (void *)do_another_thing,
(void *)&common) != 0) {
perror("pthread_create");
exit(1);
}
if (pthread_join(thread1, NULL) != 0) {
perror("pthread_join");
exit(1);
}
if (pthread_join(thread2, NULL) != 0) {
perror("pthread_join");
exit(1);
}
do_wrap_up(common);
return 0;
}
void do_one_thing(int *pnum_times) {
int i, j, x;
unsigned long k;
int work;
for (i = 0; i < 50; i++) {
// pthread_mutex_lock(&mut);
printf("doing one thing\n");
work = *pnum_times;
printf("counter = %d\n", work);
work++; /* increment, but not write */
for (k = 0; k < 500000; k++)
; /* long cycle */
*pnum_times = work; /* write back */
// pthread_mutex_unlock(&mut);
}
}
void do_another_thing(int *pnum_times) {
int i, j, x;
unsigned long k;
int work;
for (i = 0; i < 50; i++) {
// pthread_mutex_lock(&mut);
printf("doing another thing\n");
work = *pnum_times;
printf("counter = %d\n", work);
work++; /* increment, but not write */
for (k = 0; k < 500000; k++)
; /* long cycle */
*pnum_times = work; /* write back */
// pthread_mutex_unlock(&mut);
}
}
void do_wrap_up(int counter) {
int total;
printf("All done, counter = %d\n", counter);
}