-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpthread_mutex.c
More file actions
57 lines (40 loc) · 789 Bytes
/
Copy pathpthread_mutex.c
File metadata and controls
57 lines (40 loc) · 789 Bytes
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
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t lock;
void *thread_f(void *d)
{
int *ptr = d;
while (1) {
sleep(1);
pthread_mutex_lock(&lock);
(*ptr) ++;
pthread_mutex_unlock(&lock);
}
}
int main()
{
int t = 4;
pthread_t tid;
pthread_attr_t attr;
int ret;
ret = pthread_attr_init(&attr);
if (ret < 0) {
return -1;
}
ret = pthread_mutex_init(&lock, NULL);
if (ret < 0) {
return -1;
}
ret = pthread_create(&tid, &attr, thread_f, &t);
if (ret < 0) {
return -1;
}
while (1) {
pthread_mutex_lock(&lock);
printf("t value %d\n", t);
pthread_mutex_unlock(&lock);
sleep(1);
}
return 0;
};