You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
1.3 KiB
54 lines
1.3 KiB
2 years ago
|
|
||
|
function SemaphoreDisposed(message) { this.message = message || "Semaphore was disposed"; Object.freeze(this); }
|
||
|
|
||
|
const new_id = () => {
|
||
|
|
||
|
};
|
||
|
apsdajod XXX: eh, this isn't working...
|
||
|
|
||
|
function Semaphore(cap)
|
||
|
{
|
||
|
|
||
|
function Handle(next, id)
|
||
|
{
|
||
|
this.state = next;
|
||
|
this.id = id || new_id();
|
||
|
}
|
||
|
|
||
|
Handle.create = function(resolve, reject, id) {
|
||
|
let handle = new Handle(this, id);
|
||
|
handle.state[handle.id] = (error) => error ? reject(error) : resolve();
|
||
|
return handle;
|
||
|
};
|
||
|
|
||
|
// Waiters for the seamphore
|
||
|
var next = {
|
||
|
waiters: {},
|
||
|
// Push a waiter into the queue and return a promise for when it completes
|
||
|
wait: () => {
|
||
|
new Promise((resolve, reject) => { // next.waiters.push(error => error ? reject(error) : resolve()))
|
||
|
return Handle.create(resolve, reject).bind(next);
|
||
|
});
|
||
|
},
|
||
|
// Pop a waiter from the queue and complete its promise (with an optional truthy error)
|
||
|
add: (error) => { if(next.waiters.length>0) next.waiters.shift()(error); },
|
||
|
// Complete all semaphores, with an optional truthy error for rejection
|
||
|
flush: (reject) => {
|
||
|
while(next.waiters.length>0) next.waiters.shift()(reject);
|
||
|
},
|
||
|
// Dispose all semaphores in the waiter
|
||
|
dispose: (message) => next.flush(new SemaphoreDisposed(message))
|
||
|
};
|
||
|
|
||
|
this.capacity = cap;
|
||
|
this.length = 0;
|
||
|
|
||
|
this.acquire = async () => {
|
||
|
|
||
|
};
|
||
|
|
||
|
this.release = () => {
|
||
|
|
||
|
};
|
||
|
}
|