How to run functions in parallel?

后端 未结 6 1030
我在风中等你
我在风中等你 2020-11-22 10:32

I researched first and couldn\'t find an answer to my question. I am trying to run multiple functions in parallel in Python.

I have something like this:



        
6条回答
  •  伪装坚强ぢ
    2020-11-22 11:13

    You could use threading or multiprocessing.

    Due to peculiarities of CPython, threading is unlikely to achieve true parallelism. For this reason, multiprocessing is generally a better bet.

    Here is a complete example:

    from multiprocessing import Process
    
    def func1():
      print 'func1: starting'
      for i in xrange(10000000): pass
      print 'func1: finishing'
    
    def func2():
      print 'func2: starting'
      for i in xrange(10000000): pass
      print 'func2: finishing'
    
    if __name__ == '__main__':
      p1 = Process(target=func1)
      p1.start()
      p2 = Process(target=func2)
      p2.start()
      p1.join()
      p2.join()
    

    The mechanics of starting/joining child processes can easily be encapsulated into a function along the lines of your runBothFunc:

    def runInParallel(*fns):
      proc = []
      for fn in fns:
        p = Process(target=fn)
        p.start()
        proc.append(p)
      for p in proc:
        p.join()
    
    runInParallel(func1, func2)
    

提交回复
热议问题