Skip to content

Why do I need to create a new Semaphore instance every time in doSomething? #249

@izhouteng

Description

@izhouteng

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()
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions