-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchopstick.cpp
More file actions
47 lines (34 loc) · 815 Bytes
/
chopstick.cpp
File metadata and controls
47 lines (34 loc) · 815 Bytes
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
#include "chopstick.h"
#include <sys/mman.h>
void chopstick::initialize_semaphore() {
sem = (sem_t*) mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if(sem_init(sem, 1, 1) < 0)
throw "Error initializing chopstick " + _id;
}
chopstick::chopstick() : _id(0) {
initialize_semaphore();
}
chopstick::chopstick(int id) : _id(id) {
initialize_semaphore();
}
int chopstick::get_id() {
return _id;
}
int chopstick::get_value() {
int val;
sem_getvalue(sem, &val);
return val;
}
int chopstick::pick_up() {
return sem_wait(sem);
}
int chopstick::put_down() {
return sem_post(sem);
}
int chopstick::try_to_pick() {
return sem_trywait(sem);
}
void chopstick::destroy() {
sem_destroy(sem);
munmap(sem, sizeof(sem_t));
}