Python:使用线程求解多个线性系统

标签 python math scipy

我正在尝试使用线程解决使用 python 和 scipy 的多个线性系统。在 python 线程方面,我绝对是初学者。我附上了提取我想要完成的事情的代码。此代码有效,但执行时间实际上随着 totalThreads 的增加而增加。我的猜测是 spsolve 被视为关键部分,实际上并没有同时运行。

我的问题如下:

  • spsolve 是线程安全的吗?
  • 如果 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 的线程模块不会让您利用多核。这是由于称为全局解释器锁 (GIL) 的东西,它是标准 cPython 实现的关键部分。有关更多信息,请参见此处:What is a global interpreter lock (GIL)?

您应该考虑改用多处理模块,它通过启动多个独立的 Python 进程来绕过 GIL。这使用起来有点困难,因为不同的进程有不同的内存空间,所以你不能只在所有进程之间共享一个线程安全的对象并期望该对象在所有进程之间保持同步。这是对多处理的精彩介绍:http://www.doughellmann.com/PyMOTW/multiprocessing/

关于Python:使用线程求解多个线性系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708637/

相关文章:

python - 在Python中高精度地找到由(x,y)数据给出的两条曲线的交点

python - MySQL 没有建立与数据库的连接

python - pip 在 vi​​rtualenv 中的缓存在哪里?

algorithm - k-means 中的初始质心

c# - 如何编写对称版本的对齐值公式(在 C# 中)

python - Numba 中的稀疏矩阵

python - 使用 numpy 和 matplotlib 进行 13 维矩阵的 KDE(核密度估计)

Python 包 - ImportError

python - 为什么 tarfile 模块不允许压缩 append ?

python - 如何从python中的随机分布中找到指数曲线(和曲线)下的面积?