I have two methods: a() and b(). While I’m fine with multiple threads accessing any of the methods at the same time (that is desirable), I do not want any threads to enter a() while b() is being executed.
How do I do that?
Edit 1
Lets say there are 4 threads and Thread 1 is accessing A(). What I want is all of the 4 threads should not use B().
CHECK UPDATE at the bottom – I don’t think this approach can work. Leaving it for information.
You could use a Semaphore:
b(), a thread trying to executea()will block until the execution ofb()is over.b()and a second thread tries to runb()it will be able toa()whileb()is not being executed both will runNote: once a thread is in
a()and has passed the “semaphore test”, another thread can start runningb()before the end ofa()The principle should work but I have not tested it.
EDIT
Your intention is not clear and your question has been edited because one of your comments says that you want
a()andb()to be mutually exclusive (many threads can run eithera()orb()in parallel, buta()andb()should never be run in parallel). In that case, you can use the same logic with 2 semaphoresinAandinB.UPDATE => BUG
As pointed out by @yshavit in a comment to another answer, there is a race condition in the code in the following scenario:
a()and acquiresinBb()and fails to acquireinBinBa()and manages to acquireinBalthough T2 is runningb()It seems that this can’t be achieved with Sempahores only. This answer gives a better solution.