Python类实例在新线程中启动方法

标签 python multithreading class

我花了最后一个小时(s???)寻找/谷歌搜索一种方法,让类在实例化后立即在新线程中启动其方法之一。

我可以这样运行:

x = myClass()

def updater():
    while True:
        x.update()
        sleep(0.01)

update_thread = Thread(target=updater) 
update_thread.daemon = True
update_thread.start()

一个更优雅的方法是让类在实例化时在 init 中执行它。 想象一下有 10 个该类的实例...... 直到现在我都找不到解决这个问题的(有效的)解决方案...... 实际的类是一个计时器,方法是更新所有计数器变量的更新方法。由于此类还必须在给定时间运行函数,所以时间更新不会被主线程阻塞是很重要的。

非常感谢任何帮助。提前致谢...

最佳答案

在这种特定情况下,您可以直接从 Thread 继承

from threading import Thread

class MyClass(Thread):
    def __init__(self, other, arguments, here):
        super(MyClass, self).__init__()
        self.daemon = True
        self.cancelled = False
        # do other initialization here

    def run(self):
        """Overloaded Thread.run, runs the update 
        method once per every 10 milliseconds."""

        while not self.cancelled:
            self.update()
            sleep(0.01)

    def cancel(self):
        """End this timer thread"""
        self.cancelled = True

    def update(self):
        """Update the counters"""
        pass

my_class_instance = MyClass()

# explicit start is better than implicit start in constructor
my_class_instance.start()

# you can kill the thread with
my_class_instance.cancel()

关于Python类实例在新线程中启动方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416116/

相关文章:

python - 将模块和应用程序安装到离线系统的规范方法

python - 将数据从 Django View 传递到 D3

c - 为什么需要围绕 pthread 等待条件的 while 循环?

Java 类可访问性

c++ - 我的将随机生成的数字创建到数组中的程序不断崩溃

Python 和 C IPC

python类默认参数

java - 同步方法重写 - 线程获取哪个对象的锁?

Java-单线程和多线程的压缩差异

c++ - 在类中声明一个数组。 C++