-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrw_serial.c
79 lines (70 loc) · 1.67 KB
/
rw_serial.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
72
73
74
75
76
77
78
79
/*
* r/w serializer
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "rw_serial.h"
long* read_data()
{
int key = rand() % SIZE;
usleep(rand() % 10 * DELAY);
return (long *) database[key];
}
void* write_data()
{
int key = rand() % SIZE;
usleep(rand() % 10 * DELAY);
database[key] = key;
return NULL;
}
cond_t read_queue_cond()
{
return Crowd_Empty(serializer, writers_crowd);
}
cond_t write_queue_cond()
{
return (Crowd_Empty(serializer, readers_crowd) &&
Crowd_Empty(serializer, writers_crowd));
}
void create()
{
// Init database
int i;
srand(time(NULL));
for (i = 0; i < SIZE; i++)
database[i] = rand();
// Init Serializer
serializer = Create_Serial();
waiting_q = Create_Queue(serializer);
readers_crowd = Create_Crowd(serializer);
writers_crowd = Create_Crowd(serializer);
gs = serializer;
gs->rd_crowd = readers_crowd;
gs->wr_crowd = writers_crowd;
}
void *read_func(void *id)
{
long tid;
tid = (long)id;
Serial_Enter(serializer);// dequeue from the enter queue
printf("Reader thread #%ld starts!\n", tid);
Serial_Enqueue(serializer, waiting_q, &read_queue_cond, 0);// enter waiting queue, leave serializer,
Serial_Join_Crowd(serializer, readers_crowd,(void *) (&read_data));
Serial_Exit(serializer);
printf("Reader thread #%ld ends!\n", tid);
pthread_exit(NULL);
}
void *write_func(void *id)
{
long tid;
tid = (long)id;
Serial_Enter(serializer);
printf("Writer thread #%ld starts!\n", tid);
Serial_Enqueue(serializer, waiting_q, &write_queue_cond, 0);
Serial_Join_Crowd(serializer, writers_crowd, &write_data);
Serial_Exit(serializer);
printf("Writer thread #%ld ends!\n", tid);
pthread_exit(NULL);
}