gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:42 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com