使用单独的线程创建对象

2024-10-01 15:43:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个类的实例,但问题是所述类的__init__部分有些耗时,同时还有其他事情要做。在本例中,我将使用虚拟类,创建一个具有2048位素数的对象,该素数的速度非常慢,非常明显:

from Crypto.Util import number

class Gui(QMainWindow):
    def __init__(self):
        # SNIP: Set up GUI and various other
        self.slowPoke = SlowPoke()

class SlowPoke():
    def __init__(self, arg1, arg2):
        self.ready = False
        # SNIP: Set some self.basic stuff that takes practically no time at all from arg1
        self.largeprime = number.getPrime(2048)
        self.ready = True

我现在真的不需要self.slowPoke,所以有没有一种方法可以让它在一个单独的线程中创建,然后慢慢来,而Gui和主线程中的其他东西可以继续移动

我试图用concurrent.futures生成素数

with concurrent.futures.ThreadPoolExecutor() as executor:
    future = executor.submit(number.getPrime(2048))
    self.largeprime = future.result()

…但延迟仍然存在。大概是因为Gui正在等待__init__个慢线程完成,而这仍然在父线程中运行


Tags: fromselfnumberinitdefgui线程snip

热门问题