Open
Description
function make_semaphore(n) {
const cell = list(0);
function the_semaphore(m) {
return m === "acquire"
? test_and_set(cell, n)
? the_semaphore("acquire")
: true
: m === "release"
? release(cell)
: error(m, "unknown request -- semaphore");
}
return the_semaphore;
}
function release(cell) {
if(head(cell) > 0) {
set_head(cell, head(cell) - 1);
}
}
function test_and_set(cell, n) {
if(head(cell) < n) {
set_head(cell, head(cell) + 1);
return false;
} else {
return true;
}
}