Last active
May 17, 2019 04:36
-
-
Save piscisaureus/89848f9633a0c147609d95491666c528 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { test, runIfMain } from "https://deno.land/std/testing/mod.ts"; | |
import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; | |
export class Latch<T> { | |
// Array of `[resolve_function, value]` tuples. | |
send_queue: Array<[() => void, T]> = [] | |
// Array of `resolve_function` values. | |
recv_queue: Array<(value: T) => void> = [] | |
send(value: T): Promise<void> { | |
const recv_resolve = this.recv_queue.shift(); | |
if (recv_resolve) { | |
recv_resolve(value); | |
return Promise.resolve(); | |
} else { | |
return new Promise((res, _) => this.send_queue.push([res, value])); | |
} | |
} | |
recv(): Promise<T> { | |
const s = this.send_queue.shift(); | |
if (s) { | |
const [send_resolve, value] = s; | |
send_resolve(); | |
return Promise.resolve(value); | |
} else { | |
return new Promise((res, _) => this.recv_queue.push(res)); | |
} | |
} | |
} | |
async function send3(latch: Latch<number>): Promise<void> { | |
await latch.send(1); | |
await latch.send(2); | |
await latch.send(3); | |
} | |
test(async function asyncLatch(): Promise<void> { | |
const latch = new Latch<number>(); | |
send3(latch); | |
assertEquals(1, await latch.recv()); | |
assertEquals(2, await latch.recv()); | |
assertEquals(3, await latch.recv()); | |
let _lastPromise = latch.recv(); | |
}); | |
runIfMain(import.meta) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment