redis-semaphore
redis-semaphore copied to clipboard
Why do I need to create a new Semaphore instance every time in doSomething?
In this example, why do we need to create a new Semaphore instance every time we call the doSomething method?
I was very confused when I first encountered this, to the point that it took me about an hour to figure out that I needed to create a new instance each time for it to work correctly.
In other languages, such as Java/C#, you only need to new a Semaphore once.
As mentioned in this issue: #155
For example:
const Semaphore = require('redis-semaphore').Semaphore
const Redis = require('ioredis')
// TypeScript
// import { Semaphore } from 'redis-semaphore'
// import Redis from 'ioredis'
const redisClient = new Redis()
async function doSomething() {
const semaphore = new Semaphore(redisClient, 'lockingResource', 5)
await semaphore.acquire()
try {
// maximum 5 simultaneous executions
} finally {
await semaphore.release()
}
}
Why not:
const Semaphore = require('redis-semaphore').Semaphore
const Redis = require('ioredis')
// TypeScript
// import { Semaphore } from 'redis-semaphore'
// import Redis from 'ioredis'
const redisClient = new Redis()
const semaphore = new Semaphore(redisClient, 'lockingResource', 5)
async function doSomething() {
await semaphore.acquire()
try {
// maximum 5 simultaneous executions
} finally {
await semaphore.release()
}
}
Hi. Because there are internal data/state in each instance such as identifier, refresh interval, "lost lock" behaviour etc.
Lifecycle of Mutex/Semaphore implies that the instance will be created just before the locking starts and will be destroyed right after lock release.