如何正确确保使用共享锁的线程终止?



__main__中,我创建了一个新的守护进程线程,以实现对受threading.Lock()保护的共享状态的非阻塞处理。虽然从程序运行时的外观来看一切正常,但我在退出程序时偶尔会出现异常,即当守护进程线程应该终止时:

">

NoneType"对象没有属性"获取">

代码大致如下:

mutex = threading.Lock()
def async_processing(shared):
global mutex
while True:
sleep(1)
mutex.acquire()
try:
shared.modify_state()
finally:
mutex.release()

if __name__ == '__main__':
shared = SomeObject()
thread = threading.Thread(target=async_processing, args=(shared,))
thread.daemon = True
thread.start()
if user_enters_some_command_to_stdin:       
mutex.acquire()
try:
shared.modify_state()
finally:
mutex.release()

我对 Python 并不真正熟悉,因此可能没有按照应有的方式执行此操作,但我的猜测是,在mutex不再可用后,以某种方式发生了对线程的上下文切换。这个假设是真的吗?

处理此问题的最佳方法是什么?

我认为最简单的方法是添加一个标志变量:

mutex = threading.Lock()
flag = True
def async_processing(shared):
while flag:
sleep(1)
with mutex:
shared.modify_state()

if __name__ == '__main__':
shared = SomeObject()
thread = threading.Thread(target=async_processing, args=(shared,))
thread.start()
if some_user_action:        
with mutex:
shared.modify_state()
flag = False
thread.join()  # wait for exit.