首页 > 解决方案 > 如何正确确保终止使用共享锁的线程?

问题描述

__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不再可用之后。这个假设是真的吗?

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

标签: pythonmultithreadingpython-multithreading

解决方案


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

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.

推荐阅读