-
Notifications
You must be signed in to change notification settings - Fork 0
/
readerswriters.c
72 lines (56 loc) · 1.75 KB
/
readerswriters.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
#include "readerswriters.h"
bool READERSWRITERS_Init() {
ASSERT_PRINT("Entering:READERSWRITERS_Init()\n");
/*
m_semReaders = 0;
m_semWriters = 0;
*/
m_nReaders = 0;
// initialize the Readers & Writers variables
if (sem_init(&m_semReaders, 0, 1) == -1)
return FALSE;
if (sem_init(&m_semWriters, 0, 1) == -1)
return FALSE;
m_nReaders = 0;
ASSERT_PRINT("Exiting:READERSWRITERS_Init()\n");
}
void READERSWRITERS_Destroy() {
ASSERT_PRINT("Entering:READERSWRITERS_Destroy()\n");
sem_destroy(&m_semWriters);
sem_destroy(&m_semReaders);
ASSERT_PRINT("Exiting:READERSWRITERS_Destroy()\n");
}
void READERSWRITERS_LockDataRead() {
ASSERT_PRINT("Entering:READERSWRITERS_LockDataRead()\n");
// P( semReaders )
sem_wait(&m_semReaders);
m_nReaders++;
if (m_nReaders == 1) {
// P( semWriters )
sem_wait(&m_semWriters);
}
// V( semReaders )
sem_post(&m_semReaders);
ASSERT_PRINT("Exiting:READERSWRITERS_LockDataRead()\n");
}
void READERSWRITERS_UnlockDataRead() {
ASSERT_PRINT("Entering:READERSWRITERS_UnlockDataRead()\n");
sem_wait(&m_semReaders);
m_nReaders--;
if (m_nReaders == 0) {
sem_post(&m_semWriters);
}
sem_post(&m_semReaders);
ASSERT_PRINT("Exiting:READERSWRITERS_UnlockDataRead()\n");
}
void READERSWRITERS_LockDataWrite() {
ASSERT_PRINT("Entering:READERSWRITERS_LockDataWrite()\n");
sem_wait(&m_semWriters);
ASSERT_PRINT("Exiting:READERSWRITERS_LockDataWrite()\n");
}
void READERSWRITERS_UnlockDataWrite() {
ASSERT_PRINT("Entering:READERSWRITERS_UnlockDataWrite()\n");
// V( semWriters )
sem_post(&m_semWriters);
ASSERT_PRINT("Exiting:READERSWRITERS_UnlockDataWrite()\n");
}