線程基礎
看看在threading
模塊。
一個例子:
from threading import Thread
# instanciate a new thread
t = Thread(target=my_task)
# let it do the time-consuming stuff
t.start()
# do extra stuff while t is working
do_extra_stuff()
# wait for t to finish
t.join()
獲取任務結果
不過,如果你想從my_task
一個值,你需要要麼使用全局變量,可變參數或包裹你的任務進入一個等級Thread
。
下面是用包裝類的例子:
class MyThread(Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.result = None
def run(self): # this is the Thread method you need to override
# the time consuming stuff
self.result = some_result
# same as before, but using the new class, so no need to specify target.
t = MyThread()
t.start() # will call t.run() for you. Never call t.run yourself (you'll lose every benefit from using Thread)
t.join() # wait for t to be finished before getting result
print(t.result)
傳遞參數
要將參數傳遞任務(包括回調),你可以把它們作爲類字段,並在填補他們construcor,或使用args
kwarg從Thread
的construcor,像這樣:
t = Thread(target=task_with_parametters, args=(arg1, arg2))
Thread
無線我會打電話task_with_parametters
像這樣:
task_with_parametters(arg1, arg2)
我可以使用這種方法實現回調嗎? – MiDaa
用新的例子編輯,這是你需要的嗎? –
感謝您的幫助!部分是的,但是連接仍然阻塞主線程,當線程完成它的工作時,我需要一個回調機制,它調用一個函數(這個函數在我們構造線程時以某種方式定義)。 – MiDaa