线程基础
看看在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