from threading import Thread
from time import sleep
from random import randint
def f(i):
sleep(randint(1, 3))
print(f'function called from Thread {i}')
for i in range(5):
Thread(target=f, args=(i,)).start()
和输出
function called from Thread 4
function called from Thread 3
function called from Thread 1
function called from Thread 0
function called from Thread 2
@background
def your_function(argument):
time.sleep(5)
print('function finished for '+str(argument))
for i in range(10):
your_function(i)
print('loop finished')
这将产生以下输出:
loop finished
function finished for 4
function finished for 8
function finished for 0
function finished for 3
function finished for 6
function finished for 2
function finished for 5
function finished for 7
function finished for 9
function finished for 1
您可以使用Thread对象
和输出
这是2020年最简单的方法强> (它独立地运行每个迭代&这在ubuntu和Windows上都有效)
您可以使用asyncio。(可在此处找到文档)。它被用作多个Python异步框架的基础,它提供高性能的网络和Web服务器、数据库连接库、分布式任务队列等。此外,它还具有高级和低级API来适应任何类型的问题。p>
现在,无论何时调用此函数,都将并行运行,而不会将主程序置于等待状态。您也可以使用它来并行化for循环。当调用for循环时,虽然循环是顺序的,但每次迭代都会在解释器到达主程序时与主程序并行运行。例如:
这将产生以下输出:
相关问题 更多 >
编程相关推荐