Using a separate thread to create the object

Viewed 95

I need to create an instance of a class, but the problem is that the __init__ part of said class is somewhat time-consuming, and there's other stuff to do in the meantime. I'll use dummy classes for this example, creating an object with a 2048 bit prime, which is slow enough to really be noticeable:

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

I do not really need self.slowPoke right away, so is there a way I can have it created in a separate thread and just take its time, while the Gui and other stuff in the main thread can keep moving?

I tried to generate the prime with concurrent.futures

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

...but the delay still happens. Presumably because the Gui is waiting for __init__ of SlowPoke to finish, and that's still running in the parent thread.

0 Answers
Related