-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemaphore.ml
More file actions
40 lines (32 loc) · 821 Bytes
/
semaphore.ml
File metadata and controls
40 lines (32 loc) · 821 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
type t = {count:int ref; mutex:Mutex.t; empty:Mutex.t}
exception SemaphoreUnlockException
let create count =
let empty = Mutex.create () in
if count <> 0 then
Mutex.lock empty;
{count= ref count; mutex=Mutex.create ();
empty = empty}
let lock sem =
Mutex.lock sem.mutex;
incr sem.count;
if !(sem.count) = 1 then
Mutex.lock sem.empty;
Mutex.unlock sem.mutex
let unlock sem =
Mutex.lock sem.mutex;
if !(sem.count) = 0 then
begin
Mutex.unlock (sem.mutex);
raise SemaphoreUnlockException
end
else
begin
let oldval = !(sem.count) in
decr sem.count;
if oldval = 1 then
Mutex.unlock sem.empty;
Mutex.unlock sem.mutex
end
let wait_empty sem =
Mutex.lock sem.empty;
Mutex.unlock sem.empty