python如何实现并行_如何在Python中进行并行编程?

For C++, we can use OpenMP to do parallel programming; however, OpenMP will not work for Python. What should I do if I want to parallel some parts of my python program?

The structure of the code may be considered as:

solve1(A)

solve2(B)

Where solve1 and solve2 are two independent function. How to run this kind of code in parallel instead of in sequence in order to reduce the running time?

Hope someone can help me. Thanks very much in advance.

The code is:

def solve(Q, G, n):

i = 0

tol = 10 ** -4

while i < 1000:

inneropt, partition, x = setinner(Q, G, n)

outeropt = setouter(Q, G, n)

if (outeropt - inneropt) / (1 + abs(outeropt) + abs(inneropt)) < tol:

break

node1 = partition[0]

node2 = partition[1]

G = updateGraph(G, node1, node2)

if i == 999:

print "Maximum iteration reaches"

print inneropt

Where setinner and setouter are two independent functions. That's where I want to parallel...

解决方案

You can use the multiprocessing module. For this case I might use a processing pool:

from multiprocessing import Pool

pool = Pool()

result1 = pool.apply_async(solve1, [A]) # evaluate "solve1(A)" asynchronously

result2 = pool.apply_async(solve2, [B]) # evaluate "solve2(B)" asynchronously

answer1 = result1.get(timeout=10)

answer2 = result2.get(timeout=10)

This will spawn processes that can do generic work for you. Since we did not pass processes, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.

If you want to map a list to a single function you would do this:

args = [A, B]

results = pool.map(solve1, args)

Don't use threads because the GIL locks any operations on python objects.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值