如何使用固定数量的工作者处理无限队列?

ijxebb2r  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(293)

我正在为一个web应用程序进行缓存失效处理。期望的行为是,当有人访问配置文件页面时,将触发对该用户数据的重述。我只想一次最多运行k个更新作业。
我提出了以下javascript来创建异步迭代器,在等待输入时可以阻止该迭代器:

  1. const pipeline = {
  2. queue: [],
  3. resolve: null,
  4. hold: null,
  5. [Symbol.asyncIterator]() {
  6. return {
  7. async next() {
  8. while(pipeline.queue.length === 0) {
  9. if(pipeline.hold === null) {
  10. pipeline.hold = new Promise(resolve => {
  11. pipeline.resolve = resolve
  12. })
  13. }
  14. await pipeline.hold
  15. pipeline.hold = null
  16. }
  17. return Promise.resolve({
  18. done: false, value: pipeline.queue.shift()
  19. })
  20. }
  21. }
  22. },
  23. enqueue(id) {
  24. this.queue.push(id)
  25. const resolve = this.resolve
  26. this.resolve = null
  27. resolve?.()
  28. },
  29. }

我用来处理队列的代码是按照异步批处理建模的:

  1. const next = async () => {
  2. await Promise.all(
  3. Array(5).fill(null).map(async (_, idx) => {
  4. for await (let id of pipeline) {
  5. await handler(id, idx)
  6. }
  7. })
  8. )
  9. }

如果我从包含超过k个元素的队列开始,那么所有插槽都将用于处理。如果我从一个或两个元素开始,它只使用前两个插槽。
有人看到我逻辑上的缺陷吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题