forked from sakshamchecker/Hacktoberfest-21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readerwriterusingmutex.c
57 lines (57 loc) · 946 Bytes
/
readerwriterusingmutex.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
#include<stdio.h>
#include<pthread.h>
#include<string.h>
void* reader (void*);
void* writer (void*);
int getItemforBuff();
void readItemformBuff(int buffer);
int buff;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int flag =0;
int main()
{
pthread_t rd_tid;
pthread_t wr_tid;
pthread_create(&wr_tid,NULL,writer,NULL);
pthread_create(&rd_tid,NULL,reader,NULL);
pthread_join(wr_tid,NULL);
pthread_join(rd_tid,NULL);
return 0;
}
void* reader(void *argp)
{
while(1)
{
pthread_mutex_lock(&mut);
if(flag == 1)
{
readItemformBuff (buff);
flag = 0;
}
pthread_mutex_unlock(&mut);
}
}
void* writer(void *argp)
{
while(1)
{
pthread_mutex_lock(&mut);
if(flag == 0)
{
buff = getItemforBuff();
flag = 1;
}
pthread_mutex_unlock(&mut);
}
}
int getItemforBuff()
{
int item;
printf("\n writer : \n Enter an item into buffer: ");
scanf("%d",&item);
return item;
}
void readItemformBuff(int buffer)
{
printf("\n reader : read item from buffer = %d\n",buffer);
}