Skip to content

Solution to Exercise 3.47 #838

Open
Open
@clean99

Description

@clean99
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;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions