簡體   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