-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.c
64 lines (51 loc) · 1.22 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
//gcc -Wall mutex.c -lpthread
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 100
#define NUM_STEPS 100000
int sum = 0 ;
pthread_mutex_t mutex ;
void *threadBody(void *id)
{
int i ;
for (i=0; i< NUM_STEPS; i++)
{
pthread_mutex_lock (&mutex) ;
sum += 1 ; // critical section
pthread_mutex_unlock (&mutex) ;
}
pthread_exit (NULL) ;
}
int main (int argc, char *argv[])
{
pthread_t thread [NUM_THREADS] ;
pthread_attr_t attr ;
long i, status ;
pthread_mutex_init (&mutex, NULL) ;
pthread_attr_init (&attr) ;
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) ;
// create threads
for(i=0; i<NUM_THREADS; i++)
{
status = pthread_create (&thread[i], &attr, threadBody, (void *) i) ;
if (status)
{
perror ("pthread_create") ;
exit (1) ;
}
}
// wait all threads to finish
for (i=0; i<NUM_THREADS; i++)
{
status = pthread_join (thread[i], NULL) ;
if (status)
{
perror ("pthread_join") ;
exit (1) ;
}
}
printf ("Sum should be %d and is %d\n", NUM_THREADS*NUM_STEPS, sum) ;
pthread_attr_destroy (&attr) ;
pthread_exit (NULL) ;
}