Last active
April 16, 2021 09:52
-
-
Save safareli/7dc410268c6c3b3f35383e6e4693ff44 to your computer and use it in GitHub Desktop.
This file contains 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 { 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