A series of functions to help with synchronisation
A standard barrier synchronisation mechanism; the basic notion is: given a size and some function F it provides a function to "hit" the barrier. Once the barrier is hit 'size' times, F is called.
Implementation dependent decisions:
- Will error if 'hit' (or 'raise' or 'fail') is called when the barrier is already open
Barrier(size: number, callback: (error: null | Error) => void): {
hit: () => void,
raise: (amount: number) => void,
fail: (error: Error) => void
}
PromiseBarrier(size: numbergit a): {
hit: () => void,
raise: (amount: number) => void,
fail: (error: Error) => void
} & Promise<void>
PromisePoolBarrier({
poolsize: number;
barriersize: number;
start(index: number): Promise<void>;
}): Promise<void>;
Barrier:
import { Barrier } from '@numbereight/synchronisation';
function done(error: null | Error) {
if(error === null) {
console.log(`Completed Successfully`);
} else {
console.log(`Errored`, error);
}
}
const barrier = Barrier(2, done);
PromiseBarrier:
import { PromiseBarrier } from '@numbereight/synchronisation';
const barrier = PromiseBarrier(2, done);
barrier.then(
() => console.log(`Completed Successfully`),
(error) => console.log(`Errored`, error)
);
PromisePoolBarrier:
import { PromisePoolBarrier } from '@numbereight/synchronisation';
const barrier = PromisePoolBarrier({
poolsize: 2,
barriersize: 10,
async start(i: number) {
// Do my thing
}
});
await barrier.catch(e => {
/* error handling */
throw e;
})
// All of the PromisePoolBarrier things are now done.
barrier.hit();
// Nothing happens
barrier.hit();
// "Completed Successfully" is printed to console
try {
// will throw an Error as the barrier is already open
barrier.hit();
} catch(e) {
console.log(e);
}
barrier.hit();
// Nothing happens
barrier.raise(2);
barrier.hit();
barrier.hit();
barrier.hit();
// "Completed Successfully" is printed to console
try {
// will throw an Error as the barrier is already open
barrier.raise();
} catch(e) {
console.log(e);
}
barrier.hit();
// Nothing happens
barrier.fail(new Error(`Oh no, it failed`));
// "Errored Error: Oh no, it failed" printed to console (with stack)
try {
// will throw an Error as the barrier is already open
barrier.hit();
} catch(e) {
console.log(e);
}