我可以在python中同时获得2个以上的锁

时间:2017-03-10 15:24:24

标签: python multithreading locking

我可以直接在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_threadB_thread之间的公平性。由于main线程首先获得A_lockA_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,如果mainA线程在其中一个获取其第二个锁之前获得第一个锁,则获取其第二个锁的第一个线程将强制执行其他线程从一开始就开始它的with语句。此外,首先获得第二个锁的线程可以再次运行(thread fairness issue)

0 个答案:

没有答案