-
Notifications
You must be signed in to change notification settings - Fork 1
/
semaphore.cpp
127 lines (120 loc) · 2.24 KB
/
semaphore.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include "port.h"
#include "semaphore.h"
#include <unistd.h>
#include <stdlib.h>
Semaphore::Semaphore(int semKey, int numSems, int val)
: m_semid(0)
, m_semflg(IPC_CREAT | 0666)
, m_semopen(false)
, m_semKey(semKey)
, m_numSems(numSems)
{
m_arg.val = (0);
if(val)
{
if(create(val))
exit(1);
}
}
int Semaphore::clear_sem()
{
int semid;
// have num-sems set to 1 so that we remove regardless of how many
// semaphores were present.
if((semid = semget(m_semKey, 1, 0666)) == -1)
{
perror("Can't get semaphore ID");
return 1;
}
if(semctl(semid, 0, IPC_RMID, m_arg) == -1)
{
perror("Can't get remove semaphore");
return 1;
}
printf("Semaphore removed.\n");
return 0;
}
int Semaphore::create(int count)
{
if((m_semid = semget(m_semKey, m_numSems, m_semflg)) == -1)
{
perror("Can't get semaphore");
return 1;
}
m_arg.val = count;
int i;
for(i = 0; i < m_numSems; ++i)
{
if(semctl(m_semid, i, SETVAL, m_arg) == -1)
{
perror("Can't set semaphore value");
return 1;
}
}
m_semopen = true;
return 0;
}
int Semaphore::get_semid()
{
int semflg = 0666;
if ((m_semid = semget(m_semKey, m_numSems, semflg)) == -1)
{
perror("Can't get semaphore ID");
return 1;
}
m_semopen = true;
return 0;
}
int Semaphore::decrement_and_wait(int nr_sem)
{
if(!m_semopen)
return 0;
struct sembuf sops;
sops.sem_num = nr_sem;
sops.sem_op = -1;
sops.sem_flg = IPC_NOWAIT;
if(semop(m_semid, &sops, 1) == -1)
{
perror("semop: semop failed.\n");
return 1;
}
sops.sem_num = nr_sem;
sops.sem_op = 0;
sops.sem_flg = SEM_UNDO;
if(semop(m_semid, &sops, 1) == -1)
{
perror("semop: semop failed.\n");
return 1;
}
return 0;
}
int Semaphore::get_mutex()
{
if(!m_semopen)
return 0;
struct sembuf sops;
sops.sem_num = 0;
sops.sem_op = -1;
sops.sem_flg = SEM_UNDO;
if(semop(m_semid, &sops, 1) == -1)
{
perror("semop: semop failed.\n");
return 1;
}
return 0;
}
int Semaphore::put_mutex()
{
if(!m_semopen)
return 0;
struct sembuf sops;
sops.sem_num = 0;
sops.sem_op = 1;
sops.sem_flg = IPC_NOWAIT;
if(semop(m_semid, &sops, 1) == -1)
{
perror("semop: semop failed.\n");
return 1;
}
return 0;
}