繁体   English   中英

如何不等功能完成python

[英]How to not wait for function to finish python

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

在代码中(示例):

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

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

提前致谢!

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

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

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

import threading

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

您应该查看用于异步请求的库,例如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),
])

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

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

要扩展blue_note,假设你有一个带参数的函数:

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

你需要像这样传递你的args:

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

注意args必须是一个元组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM