Skip to content

Instantly share code, notes, and snippets.

@piscisaureus

piscisaureus/latch.ts

Last active May 17, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.