【问题标题】:Python - execute for loop in multithreadingPython - 在多线程中执行 for 循环
【发布时间】:2019-02-06 10:03:18
【问题描述】:

我是 python 新手。 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


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      您也可以尝试导入线程概念。

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

      【讨论】:

      • 感谢您的回答。它也适用于我的项目
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2016-12-15
      • 2011-08-20
      • 2017-06-13
      • 1970-01-01
      相关资源
      最近更新 更多