我是新来的蟒蛇。 for循环遍历元件一个接一个。我想知道如何在同一时间执行的所有元素的for循环。下面是我的示例代码:
import time
def mt():
for i in range(5):
print (i)
time.sleep(1)
mt()
它打印元件逐一从for循环并等待下一个元素1秒。我想知道如何使用多线程在for循环打印在同一时间的所有元素,而无需等待下一个元素
您可以使用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()
你也可以尝试穿进口概念。
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()