Implement fast n=1 semaphore

This commit is contained in:
luaneko 2025-01-07 21:44:44 +11:00
parent ec741cb6c0
commit eab19829f2
Signed by: luaneko
GPG Key ID: 406809B8763FF07A
4 changed files with 15 additions and 7 deletions

View File

@ -104,7 +104,7 @@ export function channel<T = void>(): Channel<T> {
}
channel.sender = function sender<T>(
f: (recv: Receiver<T>) => void | PromiseLike<void>,
f: (recv: Receiver<T>) => void | PromiseLike<void>
): Sender<T> {
const { send, recv } = channel<T>();
Promise.resolve(f(recv)).then(noop).then(recv.close, recv.close);
@ -112,7 +112,7 @@ channel.sender = function sender<T>(
};
channel.receiver = function receiver<T>(
f: (send: Sender<T>) => void | PromiseLike<void>,
f: (send: Sender<T>) => void | PromiseLike<void>
): Receiver<T> {
const { send, recv } = channel<T>();
Promise.resolve(f(send)).then(noop).then(send.close, send.close);
@ -143,3 +143,11 @@ export function semaphore(count = 1) {
return acquire;
}
export function semaphore_fast() {
let last = Promise.resolve<unknown>(undefined);
return function acquire<T>(f: () => T | PromiseLike<T>) {
return (last = last.then(f, f));
};
}

View File

@ -1,5 +1,5 @@
{
"name": "@luaneko/lstd",
"version": "0.1.2",
"version": "0.1.3",
"exports": "./mod.ts"
}

View File

@ -114,7 +114,7 @@ export class TypedEmitter<T extends EventMap> {
b: any,
c: any,
d: any,
e: any,
e: any
) {
const event = this.#events[name];
if (!event) return false;

6
jit.ts
View File

@ -30,7 +30,7 @@ export class JitCompiler {
compile() {
return new Function(
...this.#args.values(),
`"use strict"; return (${this.#body});`,
`"use strict"; return (${this.#body});`
)(...this.#args.keys());
}
}
@ -99,7 +99,7 @@ export function literal(x: unknown) {
export function map<T>(
sep: string | JitFragment,
xs: Iterable<T>,
f: (value: T, index: number) => unknown,
f: (value: T, index: number) => unknown
): JitFragment {
return fragment(sep, ...Iterator.from(xs).map(f));
}
@ -107,7 +107,7 @@ export function map<T>(
export function condition(
test: unknown,
consequent: JitFragment,
alternate: JitFragment = jit``,
alternate: JitFragment = jit``
): JitFragment {
return test ? consequent : alternate;
}