对于C++,我们可以使用OpenMP进行并行编程; 但是,OpenMP不适用于Python.如果我想并行我的python程序的某些部分,我该怎么办?
代码的结构可以被认为是:
solve1(A)
solve2(B)
Run Code Online (Sandbox Code Playgroud)
哪里solve1和solve2是两个独立的功能.如何并行运行这种代码而不是按顺序运行以减少运行时间?希望可以有人帮帮我.首先十分感谢.代码是:
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
Run Code Online (Sandbox Code Playgroud)
setinner和setouter是两个独立的函数.这就是我要平行的地方......
我想并行化我的Python程序,以便它可以在运行它的机器上使用多个处理器.我的并行化非常简单,因为程序的所有并行"线程"都是独立的,并将它们的输出写入单独的文件.我不需要线程来交换信息,但是我必须知道线程何时完成,因为我的管道的某些步骤依赖于它们的输出.
可移植性很重要,因为我希望在Mac,Linux和Windows上运行任何Python版本.鉴于这些约束,哪个是最适合实现它的Python模块?我试图在线程,子进程和多处理之间做出决定,这些都似乎提供了相关的功能.
有什么想法吗?我想要最简单的便携式解决方案.
我先研究过,找不到我的问题的答案.我试图在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)
Run Code Online (Sandbox Code Playgroud)
我想调用func1和func2并让它们同时运行.这些函数不会相互交互或在同一个对象上交互.现在我必须等待func1在func2启动之前完成.我如何做以下事情:
process.py
from files import func1, func2
runBothFunc(func1(), func2()) …Run Code Online (Sandbox Code Playgroud) 我发现在Python 3.4中,很少有用于多处理/线程的不同库:多处理与线程和asyncio.
但我不知道使用哪一个或是"推荐的".他们做同样的事情,还是不同?如果是这样,哪一个用于什么?我想编写一个在我的计算机中使用多核的程序.但我不知道我应该学习哪个图书馆.
python multithreading multiprocessing python-3.x python-asyncio
据我所知,两个功能可以并行使用运行multiprocessing或threading模块,例如使在同一时间运行两个功能和Python的多重并行进程.
但以上示例仅使用打印功能.是否有可能在python中运行并行返回列表的函数,如果是,如何?
我尝试过使用线程:
from threading import Thread
def func1(x):
return [i*i for i in x]
def func2(x):
return [i*i*i for i in x]
nums = [1,2,3,4,5]
p1 = Thread(target = func1(nums)).start()
p2 = Thread(target = func2(nums)).start()
print p1
print p2
Run Code Online (Sandbox Code Playgroud)
但我得到了以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
TypeError: 'list' object is not callable …Run Code Online (Sandbox Code Playgroud)