add event and pool structures

This commit is contained in:
JOLIMAITRE Matthieu 2024-06-24 02:44:07 +02:00
parent a84450fc23
commit 513e4d3f99
3 changed files with 52 additions and 0 deletions

View file

@ -9,3 +9,5 @@ export { log_from, next, split_promise, wait } from "./lib/utils.ts";
export { Chain } from "./lib/Chain.ts"; export { Chain } from "./lib/Chain.ts";
export { Channel } from "./lib/Channel.ts"; export { Channel } from "./lib/Channel.ts";
export { Range, range } from "./lib/Range.ts"; export { Range, range } from "./lib/Range.ts";
export { Event } from "./lib/Event.ts";
export { AsyncPool } from "./lib/AsyncPool.ts";

23
src/lib/AsyncPool.ts Normal file
View file

@ -0,0 +1,23 @@
import { Event } from "./Event.ts";
export class AsyncPool {
limit;
current = 0;
current_changed = new Event<void>();
constructor(limit: number = 8) {
this.limit = limit;
}
async run(task: () => unknown) {
while (this.current >= this.limit) await this.current_changed.wait();
this.update_current(+1);
await task();
this.update_current(-1);
}
update_current(increment: number) {
this.current += increment;
this.current_changed.trigger();
}
}

27
src/lib/Event.ts Normal file
View file

@ -0,0 +1,27 @@
import { split_promise } from "../lib.ts";
export class Event<V> {
subscriber = [] as ((value: V) => unknown)[];
subscribe(callback: (value: V) => unknown) {
this.subscriber.push(callback);
}
unsubscribe(callback: (value: V) => unknown) {
const index = this.subscriber.indexOf(callback);
if (index === -1) return false;
this.subscriber.splice(index, 1);
return true;
}
trigger(value: V) {
for (const handler of this.subscriber) handler(value);
}
async wait() {
const [promise, resolver] = split_promise<V>();
this.subscribe(resolver);
await promise;
this.unsubscribe(resolver);
}
}