Skip to content

Instantly share code, notes, and snippets.

@safareli
Last active April 16, 2021 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safareli/7dc410268c6c3b3f35383e6e4693ff44 to your computer and use it in GitHub Desktop.
Save safareli/7dc410268c6c3b3f35383e6e4693ff44 to your computer and use it in GitHub Desktop.
import { Mutex } from "async-mutex";
export type MVar<T> = {
take: () => Promise<T>;
read: () => Promise<T>;
put: (newVal: T) => Promise<void>;
};
export const newMVar = function <T>(initial: T): MVar<T> {
const val = { current: initial };
const mutex = new Mutex();
let release = () => {};
return {
take: async () => {
release = await mutex.acquire();
return val.current;
},
read: async () => {
const releaseLocal = await mutex.acquire();
const res = val.current;
releaseLocal();
return res;
},
put: async (newVal: T) => {
release();
const releaseLocal = await mutex.acquire();
val.current = newVal;
releaseLocal();
},
};
};
import { Mutex } from "async-mutex";
export const newMVarSimple = function <T>(initial: T) {
const val = { current: initial };
const mutex = new Mutex();
return {
over: async (f: (value: T) => Promise<T>) =>
mutex.runExclusive(() =>
f(val.current).then((newVal) => {
val.current = newVal;
})
),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment