向Python Thread类添加新方法是否安全? [英] Is it safe to add a new method to Python Thread class?

查看:82
本文介绍了向Python Thread类添加新方法是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向Thread子类添加一个新方法,以便告诉我的工作线程优雅退出.像这样:

I want to add a new method to a Thread subclass so I can tell my working thread to exit elegantly. Like this:

class MyThread(threading.Thread):
    def __init__(self):
        ...
        self.__stop_signal = False
        self.__signal_lock = threading.Lock()
        ...

    def run(self):
        ...
        self.__signal_lock.acquire(True)
        stop_signal = self.__stop_signal
        self.__signal_lock.release()
        if stop_signal:
            return
        ...

    def stop_elegantly(self):
        self.__signal_lock.acquire(True)
        self.__stop_signal = True
        self.__signal_lock.release()

那么这样做安全吗?

thread = MyThread()
thread.start()
...
thread.stop_elegantly()

谢谢.

推荐答案

是的,看起来不错.实际上,您可以使用

Yes, it looks fine. In fact you could do it even more "elegantly" with:

def stop_elegantly(self):
    with self.__signal_lock:
        self.__stop_signal = True

实际上,我认为您甚至不需要锁来访问成员变量,因为将为子类的每个实例分配一个单独的锁.参见 answer 例如,它将stop()方法添加到threading.Thread子类中.

Actually I don't think you even need a lock to access the member variable since there'll be a separate one allocated for each instance of your subclass. See this answer for example, which adds a stop() method to the threading.Thread subclass.

这篇关于向Python Thread类添加新方法是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆