如何不等功能完成python

时间:2017-10-09 14:49:34

标签: python

我试图编写一个包含异步部分的循环。我不想每次迭代都等待这个异步部分。有没有办法不等待循环内的这个功能完成?

在代码(示例)中:

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

global a
a = 10
test() 
while(1):
    print a

提前致谢!

5 个答案:

答案 0 :(得分:9)

你可以把它放在一个线程中。而不是test()

from threading import Thread
Thread(target=test).start()
print("this will be printed immediately")

答案 1 :(得分:2)

一种简单的方法是在另一个线程中运行 test()

import threading

th = threading.Thread(target=test)
th.start()

答案 2 :(得分:0)

您应该查看用于异步请求的库,例如gevent

此处的示例:http://sdiehl.github.io/gevent-tutorial/#synchronous-asynchronous-execution

import gevent

def foo():
    print('Running in foo')
    gevent.sleep(0)
    print('Explicit context switch to foo again')

def bar():
    print('Explicit context to bar')
    gevent.sleep(0)
    print('Implicit context switch back to bar')

gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
])

答案 3 :(得分:0)

使用thread。它创建了一个新的线程,因为异步函数运行

https://www.tutorialspoint.com/python/python_multithreading.htm

答案 4 :(得分:0)

要在blue_note上展开,假设您有一个带有参数的函数:

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

您需要像这样传递参数:

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

注意args必须是一个元组。