Does this pattern synchronize the specified part of this function? Synchronization can be implemented variously; however, I would like to know if this specific pattern accomplishes synchronization.
For clarification, I would like to know if more than one thread of execution can pass between Begin and End concurrently.
let mutex = Promise.resolve()
async function sync(): Promise<void> {
await (mutex = (async () => {
await mutex.catch((err) => console.error(err));
// Begin of synchronization.
await new Promise((r) => setTimeout(r));
await new Promise((r) => setTimeout(r));
// End of synchronization.
})());
}
This excerpt from Node’s documentation may be helpful:
“The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.”
20