Reputation: 11
I need to solve the philosopher dining problem where the approach is to pick up both chopsticks if both are available only. The availability of each chopstick is stored in a semaphore (multiprocessing module) initiated with value 1.
To achieve this, I was trying to read the value stored in the semaphores but I couldn't find anything. Is there a function to get this value?
I have tried different attempts such as:
from multiprocessing import Semaphore
chopstick = Semaphore(1)
if chopstick._value == 1:
Upvotes: 1
Views: 626
Reputation: 163
The multiprocessing.Semaphore
objects have a get_value
method that you can use (refer to the Semaphore source). According to your example:
from multiprocessing import Semaphore
chopstick = Semaphore(1)
if chopstick.get_value() == 1:
...
However, in many threading and multiprocessing situations, you can't rely on the value returned, because it could change after you look at it and before you use it.
Rather, consider just trying to take the chopstick with chopstick.aquire()
. Then it will simply "take it" if it's available or wait until it is (i.e.: another process called its release()
method), without needing to know its value.
Upvotes: 2