/
pthread_thread_safe.c
59 lines (44 loc) · 945 Bytes
/
pthread_thread_safe.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/* Prototypes */
void * thread_func1(void *);
void * thread_func2(void *);
void manipVal(int);
int var = 0;
pthread_mutex_t m;
void * thread_func1(void *arg)
{
char buff[1024];
manipVal(10);
printf("%d\n", var);
return NULL;
}
void * thread_func2(void *arg)
{
char buff[20124];
manipVal(20);
printf("%d\n", var);
return NULL;
}
void manipVal(int val)
{
pthread_mutex_lock(&m);
var = val;
pthread_mutex_unlock(&m);
}
int main(void)
{
pthread_t thread1, thread2;
int ret;
ret = pthread_create(&thread1, NULL, thread_func1, NULL);
if(ret < 0)
printf("Thread creation failed\n");
ret = pthread_create(&thread2, NULL, thread_func2, NULL);
if (ret < 0)
printf("Failed to create thread\n");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}