在Python中锁定所有线程但保留一个
我有一个线程的起始点
for _ in xrange(THREADS_COUNT):
global thread_
thread_ = threading.Thread(target=self.mainWork, args=(mainProject,victims))
thread_.start()
time.sleep(5)
当如果发生时,我需要锁定所有线程,但有一个线程不锁(就是发生了如果的那个线程)。
if 'di_unread_inbox' in inbox_page:
...
而当否则的情况发生时,我需要解锁那些被锁定的线程(我觉得需要检查一下哪些线程是锁定的)。
1 个回答
3
在检查 if
条件之前,你需要先获取一个锁,然后在你完成以下两件事之一后再释放这个锁:1) 更新共享资源,或者 2) 确定这个资源不需要更新,这时应该使用另一种逻辑。这个逻辑大概是这样的:
lock = threading.Lock()
def mainWork():
# do stuff here
lock.acquire()
if 'di_unread_inbox' in inbox_page:
try:
# something in here changes inbox_page so that 'di_unread_inbox' isn't there anymore
inboxmessagelabel.set("some label")
finally:
lock.release()
else:
lock.release()
# do other stuff
如果你不需要 else
这个部分,逻辑会显得简单一些:
def mainWork():
# do stuff here
with lock:
if 'di_unread_inbox' in inbox_page:
inboxmessagelabel.set("some label")
# do other stuff