我可以直接在python中同时获得2个或更多锁吗?
from thread import allocate_lock, start_new_thread
def A_thread( A_lock ):
while 1:
with A_lock:
pass # assume complex code here
def B_thread( B_lock ):
while 1:
with B_lock:
pass # assume complex code here
A_lock = allocate_lock()
B_lock = allocate_lock()
A_thread = start_new_thread( A_thread, ( A_lock, ) )
B_thread = start_new_thread( B_thread, ( B_lock, ) )
while 1:
with A_lock and B_lock:
pass # assume complex code here
s.t。 A_lock和B_lock都应该同时授予,或者两者都不授予。
我不想以相同的顺序获取锁定,只在A_lock
B_lock
def B_thread(...)
上述代码的问题是A_thread
和B_thread
之间的公平性。由于main
线程首先获得A_lock
,A_thread
的优先级低于B_thread
可能更好的例子是
from thread import allocate_lock, start_new_thread
def A_thread( A_lock, B_lock ):
while 1:
with B_lock and A_lock:
pass # assume complex code here
A_lock = allocate_lock()
B_lock = allocate_lock()
A_thread = start_new_thread( A_thread, ( A_lock, B_lock ) )
while 1:
with A_lock and B_lock:
pass # assume complex code here
此处的问题是busy waiting
,如果main
和A
线程在其中一个获取其第二个锁之前获得第一个锁,则获取其第二个锁的第一个线程将强制执行其他线程从一开始就开始它的with
语句。此外,首先获得第二个锁的线程可以再次运行(thread fairness
issue)