-1

I've recently read up about Semaphores and get most of the logic.

Except for the fact that,

When let's say the value of Semaphore is 5, that means 5 threads can't enter the critical section, but how do we make sure these 5 threads don't try to access the same resource again causing a concurrency problem.

Is it something we are supposed to manage manually?

roro
  • 193
  • 3
  • 16
  • Your question doesn't make much sense, 5 threads *can* acquire the semaphore. And will run concurrently so can certainly cause a concurrency problem. But otherwise, yes, a semaphore has no thread affinity. Pretty doubtful that you are using the correct synchronization object. – Hans Passant Feb 19 '15 at 21:28
  • A thread attempting to acquire a semaphore (or mutex or rwlock or ...) that it already holds is generally considered a logic error and will usually cause a concurrency problem as you suspect. There are in some cases, though, "recursive" variants of those primitives that allow multiple acquisition. They're usually more complex to code, and thus not quite as fast... – twalberg Feb 19 '15 at 21:32

1 Answers1

0

I think you got it backwards :)

You create the semaphore with the count for how many concurrent threads can enter it.

Say you have five resources for doing some work, you then create the semaphore with a count of five. What this means is that the first five threads that try to enter the semaphore with WaitOne get let in, decrementing the counter in the process.

When a thread exits the protected area with Release, it increments the counter again.

If a thread attempts to enter when the count is zero or below, that thread blocks until one of the thread already "in" the semaphore exists.

This way only five threads can be "in" the protected area at any one time.