-2

I'm writing a class that will handle thread synchronisation.

It would have a begin method which would increment a counter and an end method that would de-increment a counter. It'll have another method which will block while the counter is not zero, then perform an action while holding the lock.

Its a bit like the opposite of a semaphore, because it's unlocked at zero, and can get locked multiple times, only becoming unlocked again once it's been unlocked an equal number of times.

Is there a name for this pattern?


It's a class based on the accepted answer of my question here

6
  • Unless I'm misreading, how is this not a counting semaphore?
    – Thomas Owens
    Aug 3, 2011 at 13:38
  • My understanding about semaphores is that they allow multiple (a known number of) threads to access a resource, but i want to allow other threads calling begin and end to increase/decrease a counter that gets unlocked if it's zero. Aug 3, 2011 at 13:40
  • Edited with the link to basic idea. Aug 3, 2011 at 13:43
  • You must know the number of times it can get locked. Otherwise, you have no method of determining when a new thread must wait instead of incrementing the counter and having the resource.
    – Thomas Owens
    Aug 3, 2011 at 13:44
  • 1
    Certain operations are allowed on the resource concurrently (that would be ran between a call to begin, and a call to end), however another operation must only get ran when no other operations are being ran (that's what will run when the counter is zero). Aug 3, 2011 at 13:50

2 Answers 2

1

It sounds similar to a read write lock. Allow multiple readers at one time but to write you have to be the only thing holding the lock. Replace "read" with behavior #1 and "write" with behavior #2.

2
0

I would say you have implemented a modification of the producer-consumer-constellation, where the consumer runs a method until a store is empty. Your store is the counter. Your consumer is MethodB and your producer is MethodA.

It fit's not 100 percent, because you don't block MethodB but you block in BlockedMethod. But I think this is an appropiate point of view.

Not the answer you're looking for? Browse other questions tagged or ask your own question.