import { Semaphore } from 'async-mutex'
import fs from 'fs/promises'
async function asyncProcessWithMutex() {
let semaphore = new Semaphore(3) // set to 3 because this to handle 3 async process, if you only handle 1 async use Mutex
let [isNumber, isRelease] = await semaphore.acquire()
try {
const data1 = await fs.readFile('index1.txt')
console.log(data1.toString())
const data2 = await fs.readFile('index2.txt')
console.log(data2.toString())
const data3 = await fs.readFile('index3.txt')
console.log(data3.toString())
} catch (e) {
console.error(e)
isRelease()
} finally {
isRelease()
}
}
async function asyncProcessWithoutMutex() {
try {
const data1 = await fs.readFile('index1.txt')
console.log(data1.toString())
const data2 = await fs.readFile('index2.txt')
console.log(data2.toString())
const data3 = await fs.readFile('index3.txt')
console.log(data3.toString())
} catch (e) {
console.error(e)
}
}
setInterval(async () => {
await asyncProcessWithMutex()
console.log('process with mutex
')
}, 2000)
setInterval(async () => {
await asyncProcessWithoutMutex()
console.log('process without mutex
')
}, 2500)