我尝试用python和scipy来解决多个线性系统。谈到python线程,我绝对是个初学者。我有附加的代码,提炼我要完成的。这段代码可以工作,但是执行时间实际上随着totalThreads的增加而增加。我的猜测是spsolve被视为一个关键部分,实际上并不是同时运行的。在
我的问题如下:
我一直在网上寻找答案,但没找到。也许,我只是用错了关键词。谢谢大家的帮助。在
def Worker(threadnum, totalThreads):
for i in range(threadnum,N,totalThreads):
x[:,i] = sparse.linalg.spsolve( A, b[:,i] )
threads = []
for threadnum in range(totalThreads):
t = threading.Thread(target=Worker, args=(threadnum, totalThreads))
threads.append(t)
t.start()
for threadnum in range(totalThreads): threads[threadnum].join()
首先,您应该了解,与直觉相反,Python的线程模块不允许您利用多核。这是由于一种称为全局解释器锁(Global Interpreter Lock,GIL)的东西,它是标准cPython实现的关键部分。更多信息请参见此处:What is a global interpreter lock (GIL)?
您应该考虑改用multiprocessing模块,它通过旋转多个独立的Python进程来绕过GIL。这有点难处理,因为不同的进程有不同的内存空间,所以不能只在所有进程之间共享一个线程安全对象,并期望该对象在所有进程之间保持同步。下面是对多处理的一个很好的介绍:http://www.doughellmann.com/PyMOTW/multiprocessing/
相关问题 更多 >
编程相关推荐