LeeeeeeM / blog

daily blog
0 stars 0 forks source link

设计一个并发为2的调度器 #35

Open LeeeeeeM opened 5 years ago

LeeeeeeM commented 5 years ago
class Scheduler {

  add(promiseCreator) {
  }
  // todo
}

const scdu = new Scheduler()
const timeout = time => {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

function addTask(time, order) {
  scdu.add(() => timeout(time)).then(() => console.log(order))
}

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

// 2 3 1 4
LeeeeeeM commented 5 years ago

作为一个面试题极为脑残,真服了。 我花了半天时间也没写出来,因为要反复调试,手写就是两眼一抹黑。

class Scheduler {

  constructor() {
    this.resolver = []
    this.index = 0
    this.count = 0
  }

  add(promiseCreator) {
    return new Promise(resolve => {
      this.resolver.push(resolve)
      if (this.count < 2) {
        this.publish()
      } 
    }).then(() => {
      return promiseCreator().then(() => {
        this.finish()
      })
    })
  }

  finish() {
    this.count--
    this.publish()
  }

  publish() {
    if (this.count >= 2) return
    this.count++
    const resolve = this.resolver[this.index++]
    if (resolve) resolve()
  }
}

const scdu = new Scheduler()

const timeout = time => {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

function addTask(time, order) {
  scdu.add(() => timeout(time)).then(() => console.log(order))
}

addTask(1000, 1)
addTask(500, 2)
addTask(300, 3)
addTask(400, 4)
LeeeeeeM commented 5 years ago

class Scheduler {
  constructor(max) {
    this.taskList = []
    this.max = max
    this.count = 0
    this.index = 0
  }
  add(promiseCreator) {
    return new Promise(resolve => {
      this.taskList.push(resolve)
      if (this.count < this.max) {
        this.publish()
      }
    }).then(promiseCreator).then(() => {
      this.count--
      this.publish()
    })
  }
  publish() {
    if (this.count >= this.max) return
    this.count++
    const resolve = this.taskList[this.index++]
    if (resolve) {
      resolve()
    }
  }
}

const sch = new Scheduler(3)

function timeout(time) {
  return new Promise(function(resolve) {
    setTimeout(resolve, time)
  })
}

function addTask(time, order) {
  sch.add(() => timeout(time)).then(() => console.log(order))
}

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