Python的 - 执行在多线程循环

问题描述 投票:1回答:2

我是新来的蟒蛇。 for循环遍历元件一个接一个。我想知道如何在同一时间执行的所有元素的for循环。下面是我的示例代码:

import time
def mt():
    for i in range(5):
        print (i)
        time.sleep(1)
mt()

它打印元件逐一从for循环并等待下一个元素1秒。我想知道如何使用多线程在for循环打印在同一时间的所有元素,而无需等待下一个元素

python python-3.x python-2.7 python-multiprocessing python-multithreading
2个回答
1
投票

您可以使用multiprocessing模块如下面的例子:

import time
from multiprocessing import Pool

def main():
    p = Pool(processes=5)
    result = p.map(some_func, range(5))

def some_func(i):
    print(i)
    time.sleep(1)

if __name__ == '__main__':
    main()

0
投票

你也可以尝试穿进口概念。

import threading
import time

def mt(i):
    print (i)
    time.sleep(1)

def main():
    for i in range(5):
        threadProcess = threading.Thread(name='simplethread', target=mt, args=[i])
        threadProcess.daemon = True
        threadProcess.start()
main()
© www.soinside.com 2019 - 2024. All rights reserved.