2018-03-23 04:35:52 +01:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Creates a mutual exclude function with the following property:
|
|
|
|
|
*
|
|
|
|
|
* @example
|
2018-10-29 21:58:21 +01:00
|
|
|
* const mutex = createMutex()
|
2018-11-25 03:17:00 +01:00
|
|
|
* mutex(() => {
|
2018-03-23 04:35:52 +01:00
|
|
|
* // This function is immediately executed
|
2018-11-25 03:17:00 +01:00
|
|
|
* mutex(() => {
|
|
|
|
|
* // This function is not executed, as the mutex is already active.
|
2018-03-23 04:35:52 +01:00
|
|
|
* })
|
|
|
|
|
* })
|
|
|
|
|
*
|
|
|
|
|
* @return {Function} A mutual exclude function
|
|
|
|
|
* @public
|
|
|
|
|
*/
|
2018-10-29 21:58:21 +01:00
|
|
|
export const createMutex = () => {
|
|
|
|
|
let token = true
|
|
|
|
|
return (f, g) => {
|
2018-01-10 00:17:26 +01:00
|
|
|
if (token) {
|
|
|
|
|
token = false
|
|
|
|
|
try {
|
|
|
|
|
f()
|
2018-10-29 21:58:21 +01:00
|
|
|
} finally {
|
|
|
|
|
token = true
|
2018-01-10 00:17:26 +01:00
|
|
|
}
|
2018-06-02 13:33:04 +02:00
|
|
|
} else if (g !== undefined) {
|
|
|
|
|
g()
|
2018-01-10 00:17:26 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|