/**
 * @example
 * const mutex = syncLock()
 * await mutex.lock()
 * mutex.unlock()
 */
function syncLock() {
  let lk = false
  const mutex = {}

  mutex.lock = async function() {
    while (lk) {
      await sleep(100)

      if (!lk) {
        lk = true
        return
      }
    }

    lk = true
  }

  mutex.unlock = function() {
    lk = false
  }

  return mutex
}


function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time))
}
0条评论 顺序楼层
请先登录再回复