Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

028.async-concurrent-scheduler #28

Open
mewcoder opened this issue Mar 19, 2024 · 3 comments
Open

028.async-concurrent-scheduler #28

mewcoder opened this issue Mar 19, 2024 · 3 comments

Comments

@mewcoder
Copy link
Owner

mewcoder commented Mar 19, 2024

实现一个带并发限制的异步调度器,保证同时运行的任务最多有两个。

完善下面代码中的 Scheduler 类,使得以下程序能正确输出。

// 实现
class Scheduler {
  constructor() {
    this._max = 2;
  }
  // ...
}

// 测试
const timeout = (time) =>
  new Promise((resolve) => {
    setTimeout(resolve, time);
  });

const scheduler = new Scheduler();
const addTask = (time, order) => {
  scheduler.add(() => timeout(time)).then(() => console.log(order));
};

addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');

// 期望输出: 2 3 1 4
@mewcoder
Copy link
Owner Author

mewcoder commented Mar 20, 2024

class Scheduler {
  constructor(num = 2) {
    this.max = num;
    this.queue = [];
    this.count = 0;
  }
  add(promiseCreator) {
    return new Promise((resolve) => {
      promiseCreator._resolve = resolve;  // 关键点,怎么缓存这个 resolve; reject 同理
      this.queue.push(promiseCreator);
      this.run();
    });
  }
  run() {
    if (this.count >= this.max || this.queue.length === 0) return;
    this.count++;
    const promise = this.queue.shift();
    promise()
      .then(res => {
        promise._resolve(res);
      }).finally(() => {
        this.count--;
        this.run();
      })
  }
}

@mewcoder
Copy link
Owner Author

mewcoder commented Mar 20, 2024

class Scheduler {
  constructor(num = 2) {
    this.max = num;
    this.queue = [];
    this.count = 0;
  }
  add(task) {
    return new Promise((resolve) => {
      // 用对象包装一下,保存 resolve
      this.queue.push({
        resolve,
        task
      });
      this.run();
    });
  }
  run() {
    if (this.count >= this.max || this.queue.length === 0) return;
    this.count++;
    const { task, resolve } = this.queue.shift();
    task()
      .then(res => {
        resolve(res);
      }).finally(() => {
        this.count--;
        this.run();
      })
  }
}

@mewcoder
Copy link
Owner Author

简单的变种,这个不需要缓存resolve

const urls = [
  {
    link: "link1",
    time: 1000,
  },
  {
    link: "link2",
    time: 500,
  },
  {
    link: "link3",
    time: 300,
  },
  {
    link: "link4",
    time: 400,
  },
];

// 模拟异步加载
function request(url) {
  return new Promise((resolve) => {
    console.log(url.link + "- start");
    setTimeout(() => {
      console.log(url.link + "- end");
      resolve();
    }, url.time);
  });
}

class Scheduler {
  constructor(n = 2) {
    this.max = n;
    this.currentCount = 0;
    this.taskQueue = [];
  }

  add(task) {
    this.taskQueue.push(task);
    this.run();
  }

  run() {
    if (this.taskQueue.length === 0 || this.currentCount >= this.max)
      return;

    this.currentCount++;
    const fn = this.taskQueue.shift();
    fn()
      .finally(() => {
        this.currentCount--;
        this.run();
      })
  }
}

const scheduler = new Scheduler();

urls.forEach((url) => {
  scheduler.add(() => request(url));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant