我一直在寻找一种方法来做到这一点:
代替:
await myfunc()
我想要:
limiter = Limiter(50)
await limiter(myfunc)
如果我的函数调用有 50 个待处理,限制器不会将我的函数添加到事件队列,而是会阻塞(让给其他调用者)
通过这种方式,系统会在繁忙时优雅地降级,将资源问题传播给客户端。
我研究过使用信号量和互斥体,但它们不存在,并且它们的库也有同样的问题(无限的承诺......每个等待信号量的调用者都会创建一个稍后发生的新承诺)。
这是我可怕的解决方案:
class ConcurrencyControl {
constructor(maxConcurrent) {
this.maxConcurrent = maxConcurrent;
this.currentCount = 0;
}
async acquire() {
while (this.currentCount >= this.maxConcurrent) {
await new Promise(resolve => setTimeout(resolve, 10));
}
this.currentCount++;
}
release() {
this.currentCount--;
}
run(promiseFunction) {
this.acquire().then(() => {
promiseFunction().then(() => {
this.release();
}, () => {
this.release();
});
});
return;
}
}