Forgive me if this has been asked before. I have looked around a lot, but I get the feeling that I don't have the proper vocabulary to find this by searching the web.
I have a multithreaded application in python. I want to be able to lock a certain block of code but only to other threads with a certain condition. Let me give an example: There are three threads, thread_a
, thread_b
and thread_c
. Each thread may run through the function foo
at any time. I don't want any two threads with bar
equal to each other to be able to access Code block ALPHA
at the same time. However, I don't want to block threads whose bar
value is different. In this case, let's say thread_a
has a bar == "cat"
and hits line (3)
first. Before thread_a
hits line (5)
, let's say thread_b
, with bar == "cat"
hits line (3)
. I would like for thread_b
to wait. But if thread_c
comes along, with bar == "dog"
, I would like for it to be able to keep going.
(1) def foo(bar):
(2)
(3) lock(bar)
(4) # Code block ALPHA (two threads with equivalent bar should not be in here)
(5) unlock(bar)
As another note, the possible values for bar
are completely unpredictable but with a very high chance of collision.
Thank you for any help. The library I am looking at is the python threading library
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…