简体   繁体   English

Python-在多线程中执行循环

[英]Python - execute for loop in multithreading

I am new to python. 我是python的新手。 for loop iterates element one by one. for循环逐个迭代元素。 I want to know how to execute all the elements in the for loop at the same time. 我想知道如何同时执行for循环中的所有元素。 Here is my sample code: 这是我的示例代码:

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

It prints the element one by one from for loop and wait 1 sec for next element. 它从for循环中逐一打印元素,然后等待1秒钟等待下一个元素。 I want to know how to use multi-threading in for loop to print all the elements at the same time without waiting for next element 我想知道如何在for循环中使用多线程来同时打印所有元素,而无需等待下一个元素

You can use the multiprocessing module as shown in the example below: 您可以使用多处理模块,如下例所示:

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()

You can also try import threading Concept. 您也可以尝试导入线程概念。

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()

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

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