如何不等功能完成python

Luc*_*ähn 8 python

我正在尝试编写一个带有异步部分的循环.我不想每次迭代都等待这个异步部分.有没有办法不等待循环内的这个功能完成?

在代码中(示例):

import time
def test():
    global a
    time.sleep(1)
    a += 1
    test()

global a
a = 10
test() 
while(1):
    print a
Run Code Online (Sandbox Code Playgroud)

提前致谢!

blu*_*ote 11

你可以把它放在一个线程中.代替test()

from threading import Thread
Thread(target=test).start()
print("this will be printed immediately")
Run Code Online (Sandbox Code Playgroud)


Mar*_*lle 5

为了扩展 blue_note,假设您有一个带参数的函数:

def test(b):
    global a
    time.sleep(1)
    a += 1 + b
Run Code Online (Sandbox Code Playgroud)

你需要像这样传递你的参数:

from threading import Thread
b = 1
Thread(target=test, args=(b, )).start()
print("this will be printed immediately")
Run Code Online (Sandbox Code Playgroud)

注意 args 必须是一个元组。