我正试图围绕async/await
,我有以下代码:
class AsyncQueue<T> {
queue = Array<T>()
maxSize = 1
async enqueue(x: T) {
if (this.queue.length > this.maxSize) {
// Block until available
}
this.queue.unshift(x)
}
async dequeue() {
if (this.queue.length == 0) {
// Block until available
}
return this.queue.pop()!
}
}
async function produce<T>(q: AsyncQueue, x: T) {
await q.enqueue(x)
}
async function consume<T>(q: AsyncQueue): T {
return await q.dequeue()
}
// Expecting 3 4 in the console
(async () => {
const q = new AsyncQueue<number>()
consume(q).then(console.log)
consume(q).then(console.log)
produce(q, 3)
produce(q, 4)
consume(q).then(console.log)
consume(q).then(console.log)
})()
我的问题当然是在代码的“阻塞直到可用”部分。我希望能够“停止”执行直到发生某些事情(例如,出列暂停直到出现入队,反之亦然,考虑到可用空间)。我觉得我可能需要使用协同程序,但我真的想确保我在这里没有遗漏任何async/await
魔法。
答案 0 :(得分:6)
17/04/2019更新:简而言之,下面的AsyncSemaphore实现中存在一个错误,它是使用property-based测试捕获的。 You can read all about this "tale" here。这是固定版本:
class AsyncSemaphore {
private promises = Array<() => void>()
constructor(private permits: number) {}
signal() {
this.permits += 1
if (this.promises.length > 0) this.promises.pop()!()
}
async wait() {
this.permits -= 1
if (this.permits < 0 || this.promises.length > 0)
await new Promise(r => this.promises.unshift(r))
}
}
最后,经过相当大的努力,受到@Titian答案的启发,我想我解决了这个问题。代码中填充了调试消息,但它可能会提供有关控制流的教学目的:
class AsyncQueue<T> {
waitingEnqueue = new Array<() => void>()
waitingDequeue = new Array<() => void>()
enqueuePointer = 0
dequeuePointer = 0
queue = Array<T>()
maxSize = 1
trace = 0
async enqueue(x: T) {
this.trace += 1
const localTrace = this.trace
if ((this.queue.length + 1) > this.maxSize || this.waitingDequeue.length > 0) {
console.debug(`[${localTrace}] Producer Waiting`)
this.dequeuePointer += 1
await new Promise(r => this.waitingDequeue.unshift(r))
this.waitingDequeue.pop()
console.debug(`[${localTrace}] Producer Ready`)
}
this.queue.unshift(x)
console.debug(`[${localTrace}] Enqueueing ${x} Queue is now [${this.queue.join(', ')}]`)
if (this.enqueuePointer > 0) {
console.debug(`[${localTrace}] Notify Consumer`)
this.waitingEnqueue[this.enqueuePointer-1]()
this.enqueuePointer -= 1
}
}
async dequeue() {
this.trace += 1
const localTrace = this.trace
console.debug(`[${localTrace}] Queue length before pop: ${this.queue.length}`)
if (this.queue.length == 0 || this.waitingEnqueue.length > 0) {
console.debug(`[${localTrace}] Consumer Waiting`)
this.enqueuePointer += 1
await new Promise(r => this.waitingEnqueue.unshift(r))
this.waitingEnqueue.pop()
console.debug(`[${localTrace}] Consumer Ready`)
}
const x = this.queue.pop()!
console.debug(`[${localTrace}] Queue length after pop: ${this.queue.length} Popping ${x}`)
if (this.dequeuePointer > 0) {
console.debug(`[${localTrace}] Notify Producer`)
this.waitingDequeue[this.dequeuePointer - 1]()
this.dequeuePointer -= 1
}
return x
}
}
更新:这里是一个使用AsyncSemaphore
的干净版本,它真正封装了通常使用并发原语完成的方式,但适用于异步CPS单 - 带有async/await
的thread-event-loop™样式的JavaScript。您可以看到AsyncQueue
的逻辑变得更加直观,并且通过Promises的双重同步被委托给两个semaphores:
class AsyncSemaphore {
private promises = Array<() => void>()
constructor(private permits: number) {}
signal() {
this.permits += 1
if (this.promises.length > 0) this.promises.pop()()
}
async wait() {
if (this.permits == 0 || this.promises.length > 0)
await new Promise(r => this.promises.unshift(r))
this.permits -= 1
}
}
class AsyncQueue<T> {
private queue = Array<T>()
private waitingEnqueue: AsyncSemaphore
private waitingDequeue: AsyncSemaphore
constructor(readonly maxSize: number) {
this.waitingEnqueue = new AsyncSemaphore(0)
this.waitingDequeue = new AsyncSemaphore(maxSize)
}
async enqueue(x: T) {
await this.waitingDequeue.wait()
this.queue.unshift(x)
this.waitingEnqueue.signal()
}
async dequeue() {
await this.waitingEnqueue.wait()
this.waitingDequeue.signal()
return this.queue.pop()!
}
}
更新2:上面的代码中似乎隐藏了一个微妙的错误,当尝试使用大小为0的AsyncQueue
时,这一点很明显。语义确实有意义:它是一个没有任何缓冲区的队列,发布者总是等待消费者存在。妨碍它发挥作用的是:
await this.waitingEnqueue.wait()
this.waitingDequeue.signal()
如果仔细观察,您会发现dequeue()
与enqueue()
并不完全对称。事实上,如果一个人交换这两个指令的顺序:
this.waitingDequeue.signal()
await this.waitingEnqueue.wait()
然后一切再次起作用;对我来说似乎很直观,我们在实际等待dequeuing()
之前发出了对enqueuing
感兴趣的信息。
我还不确定如果不进行大量测试,这不会重新引入细微的错误。我将此视为挑战;)