WHY DOESN"T THIS FUKCINGA I STUPID THING WORK????? RESOLVE IS ***PROVEN*** TO ____NOT____ BE CALLED IN THE PROMISE CTOR SO WHY THE FUCK IS THAT PROMISE RESOLVING IMMEDIATELY!??!?!?!??!???!??!??!?!?!?!?
if(!cap||cap<=0)throw`Semaphore capacity cannot be '${cap}', must be a number greater than 0`;
this.capacity=cap;
this.length=0;
letself=this;
// Waiters for the seamphore
// Waiters for the seamphore
varnext={
varnext={
waiters:{},
waiters:[],
// Push a waiter into the queue and return a promise for when it completes
// wait for a slot to be available, then take it. If there are slots, the promise resolves immediately, if not, it is added to the release queue and will resolve when there is one available for it.
// Pop a waiter from the queue and complete its promise (with an optional truthy error)
// release a raw lock on the semaphore. if there are pending `acquire()` promises, the length is not decremented, but the next queued up acquire is resolved insetad.
//TODO: ,dispose: (error = new SemaphoreDisposed()) => { } // reject all `waiters`, and cause all new `acquire()`s to immediately reject.
};
};
this.capacity=cap;
this.acquire_raw=async()=>{
this.length=0;
awaitnext.acquire();
};
this.acquire =async()=>{
this.release_raw=()=>{
next.release();
};
};
this.release=()=>{
/// Acquire a semaphore lock (if one is not available, wait until one is) and then run `func()` with the lock held, afterwards, release the lock and return the result of `func()`.
/// If `func` is an async function, it is awaited and the lock is released after it has resolved (or rejected), and the result of this function is the result of that promise.
this.using=async(func)=>{
//if(!func || (typeof obj !== "function" && !isPromise(func))) throw `Parameter '{func}' is not a function or Promise.`;
console.log("waiting lock...");
awaitnext.acquire();//self.acquire_raw();
console.log("running thunk...");
try{
constrv=func();
if(isPromise(rv))returnawaitrv;
elsereturnrv;
}finally{
console.log("releasing lock...");
next.release();//self.release_raw();
}
};
};
}
}
/// Create a Mutex
Semaphore.Mutex=()=>newSemaphore(1);
constsem_example=async()=>{
varsemaphore=Semaphore.Mutex();//XXX: WHY doesn't this work? acquire just reutrns immediately, even when `resolve` is proven to NOT be called in the promise body???