python - 如何并行运行函数?

标签 python multithreading multiprocessing

我首先进行了研究,但找不到我的问题的答案。我正在尝试在 Python 中并行运行多个函数。

我有这样的事情:

files.py

import common #common is a util class that handles all the IO stuff

dir1 = 'C:\folder1'
dir2 = 'C:\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15, 35, 45, 25, 5, 15, 35, 45]

def func1():
   c = common.Common()
   for i in range(len(addFiles)):
       c.createFiles(addFiles[i], filename, dir1)
       c.getFiles(dir1)
       time.sleep(10)
       c.removeFiles(addFiles[i], dir1)
       c.getFiles(dir1)

def func2():
   c = common.Common()
   for i in range(len(addFiles)):
       c.createFiles(addFiles[i], filename, dir2)
       c.getFiles(dir2)
       time.sleep(10)
       c.removeFiles(addFiles[i], dir2)
       c.getFiles(dir2)

我想调用 func1 和 func2 并让它们同时运行。这些函数不会相互交互或在同一对象上交互。现在我必须等待 func1 在 func2 开始之前完成。如何执行以下操作:

process.py

from files import func1, func2

runBothFunc(func1(), func2())

我希望能够几乎同时创建两个目录,因为我每分钟都在计算正在创建的文件数量。如果目录不存在,它会影响我的时间。

最佳答案

您可以使用 threadingmultiprocessing .

由于 peculiarities of CPython , threading 不太可能实现真正的并行性。因此,multiprocessing 通常是更好的选择。

这是一个完整的例子:

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

启动/加入子进程的机制可以很容易地按照 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)

关于python - 如何并行运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207309/

相关文章:

python - 如何安排子流程?

python - 使用 psycopg2 在 python 上进行多进程

python - dict可以在父进程和子进程之间共享吗?

python - 在其他字段发生变化时更改字段值 OpenERP/Python

java - 当队列已满时 Spring 线程和 TaskRejectException

multithreading - 从 QRunnable 发出信号或发布事件

c# - 在上一个调用仍在进行时无法重新调用 BeginGetRequestStream/BeginGetResponse

python -/usr/bin/ld : cannot find -lpython-dev on Ubuntu. 使用PyObject编译C程序

python - Ansible 条件基于文件的内容

python - 如何将 for 循环推进 2 次迭代?