python - 如何正确确保终止使用共享锁的线程?
问题描述
在__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.
推荐阅读
- python - Python Beautiful Soup 仅在文本匹配时抓取?
- javascript - 正在尝试添加帖子
- java - 使用 WebClient 时有没有办法同时获取状态和正文?
- javascript - 如何将类 ID 引入从 CSV 文件导入的数据中?
- ruby - Ruby 和 Moment.js 传递时间不会产生错误
- wordpress - googlesheet 中的时间戳错误
- c# - 在 Xamarin.Forms Android 中绘制宽图像
- javascript - Javascript 中的 List 引发意外错误
- java - 如何将值插入数据库?
- rust - 如何在 match 语句分支中声明变量?