-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmultithreads_mutex.c
71 lines (56 loc) · 1.41 KB
/
multithreads_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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
/* number of threads */
#define N 3
/* global variable incremented by threads */
uint32_t g = 0;
/* global mutex protecting g */
pthread_mutex_t mutex;
/* function to be executed by all threads */
void *my_thread(void *vargp)
{
uint32_t my_id = (uintptr_t)vargp;
uint32_t iterations = 10000;
while (iterations--)
{
uint32_t rounds = 10000, sum = 0, inc;
/* Increment global variable g with an atomic operation */
pthread_mutex_lock(&mutex);
inc = ++g;
/* sleep 0.1 milliseconds */
usleep(100);
pthread_mutex_unlock(&mutex);
while (rounds--)
{
sum += inc;
}
/* sleep 0.9 millisecond */
usleep(900);
printf("Thread %u: inc = %5u, sum = %9u\n", my_id, inc, sum);
}
}
int main()
{
pthread_t tid[N];
uint32_t i, id;
/* init mutex */
pthread_mutex_init(&mutex, NULL);
/* create N threads */
for (i = 0; i < N; i++)
{
id = i + 2;
pthread_create(&tid[i], NULL, my_thread, (void*)(uintptr_t)id);
printf("Started thread %d: %p\n", id, (void *)tid[i]);
}
/* wait for threads to terminate */
for (i = 0; i < N; i++)
{
pthread_join(tid[i], NULL);
}
/* deinit mutex */
pthread_mutex_destroy(&mutex);
exit(0);
}