python 中的并行对象初始化

Parallel object initialization in python

通常我会在特定的函数调用中使用 async,然后使用 await。但我不确定如何通过对象创建来实现它。我想触发我的三个 classes 的创建,然后等待所有初始化函数完成。所以我的输出看起来像 -

First Class
Second Class
Third Class
First Class done
Second Class done
Third Class done

(class顺序无关紧要)

class First:
    def __init__(self, x):
        print("First Class")
        sleep(60)
        print("First Class done")

class Second:
    def __init__(self, x):
        print("Second Class")
        sleep(60)
        print("Second Class done")

class Third:
    def __init__(self, x):
        print("Third Class")
        sleep(60)
        print("Third Class done")
def main():
    f = First(1)
    s = Second(2)
    t = Third(3)
    #await f,s,t init functions to finish.

您可以使用线程来做到这一点。但要注意 GIL。如果您真的想提高性能,那么您应该使用子流程。但无论如何,这里是您的问题的代码:

import threading 
from time import sleep

class First:
    def __init__(self, x):
        print("First Class")
        #sleep(60)
        print("First Class done")
        self.x = x

class Second:
    def __init__(self, x):
        print("Second Class")
        #sleep(60)
        print("Second Class done")
        self.x = x

class Third:
    def __init__(self, x):
        print("Third Class")
        #sleep(60)
        print("Third Class done")
        self.x = x

def assign(lst,i,Class):
    lst[i] = Class(i)

def main():
    lst = [None,None,None]
    t1=threading.Thread(target=assign,args=[lst,0,First])
    t2=threading.Thread(target=assign,args=[lst,1,Second])
    t3=threading.Thread(target=assign,args=[lst,2,Third])
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()
    print(lst[0].x,lst[1].x,lst[2].x)
    
if __name__ == "__main__":
    main()