python线程模块: Is overriding run() necessary

标签 python python-multithreading

我正在阅读教程来了解多线程,并且到处都看到人们重写 run 方法。我不清楚from the doc

This class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the init() and run() methods of this class.

Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.**

那么如何创建一个界面,让用户可以在自己的单独线程中选择 doXdoY 呢?例如,如果需要运行,我是否必须做这样的事情?

class MyCls(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def doX(self):
        while True:
            time.slee(10)
            return 'x'

    def doY(self):
        while True:
            time.slee(10)
            return 'y'

    def run(self, dowhat):
        assert dowhat.lower() in 'xy', "Can only do X or Y"
        return getattr(self,'do'+dowhat.upper())()

用法:

o1 = MyCls()
o1.start()
o1.run('x')
#separate thread
o2 = MyCls()
o2.start()
o2.run('y')

是否有任何方法可以方便地执行 o1.doX() ,从而在自己的线程中执行 doX() ?

最佳答案

在这种情况下,您甚至不需要子类化线程。简单

from threading import Thread 
class Thingy(object):
    @staticmethod
    def doX():
        print ("X")
    @staticmethod
    def doY():
        print ("Y")
worker1 = Thread(target=Thingy.doX).start()
worker2 = Thread(target=Thingy.doY).start()

编辑: 我想你的意思是像生成器这样的东西每次都在线程中计算?这或多或少是你想要的吗?

from threading import Thread
import time

class Thingy(object):
    def doX(self,  rng):
        for i in range(0, rng):
            worker1 = Thread(target=self.doY)
            worker1.start()
            worker1.join()
            yield self.item

    def doY(self):
        self.item = time.time()

gen = Thingy().doX(5)
print (gen.next(), str(type(gen)))
print (list(gen))

结果

(1416756265.972083, "<type 'generator'>")
[1416756265.972913, 1416756265.973542, 1416756265.974052, 1416756265.974545]

关于python线程模块: Is overriding run() necessary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088797/

相关文章:

multithreading - 如何在 Python 中接收线程回调

python - 列表是线程安全的吗?

python - 对 python asyncio gRPC 客户端的多线程支持

python - 从表中删除零

python - 在 Python 中按位置过滤 Twitter 流

python - 如何使 python 脚本在 bash 和 python 中都可以通过管道传输

python - 如何从 python 中的后台线程读取键盘输入?

python - 从 Django 1.11 升级到 Django 2.1 后 request.POST 为空

java - 如何在 Java 中使用占位符进行字符串格式化(如在 Python 中)?

python - 以不同的顺序生成 itertools.product