断言锁的状态是否完全没有用?如何实现.haslock()?

时间:2019-02-06 14:30:28

标签: python-3.x multithreading locking

threading.Lock类提供了(未记录).locked()方法,如果锁被锁定,则返回True,否则返回False。现在我要编写这样的代码:

线程1:

def run():
     while True:
         with mylock:
              dostuff()
def configure_dostuff(args):
    assert mylock.locked()
    changeconfig_of_dostuff_which_cant_happen_when_it_runs(args)

现在线程2 应该正在做:

with mylock:
     configure_dostuff(args)

因此它可以安全地更改线程1的操作。但是.locked()永远不会检查有锁,因此,如果线程2调用configure_dostuff()却没有获得锁(由于编程错误),则断言可能不会引发错误,因为Thread1当前具有锁。

AFAIK没有Lock.haslock()方法,仅在调用线程具有锁定的情况下返回。关于如何以线程安全的方式实现此目标的任何想法?

0 个答案:

没有答案