Skip to main content
 首页 » 编程设计

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

2024年10月25日998°冷暖

我正在阅读教程以了解多线程,并且到处都看到人们重写 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.**

那么我该如何创建一个界面,让用户可以在其自己的单独线程中选择 doX 或 doY?例如,如果需要运行,我是否必须执行这样的操作?

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]