python - 使用多核在 Python 中进行线程化

标签 python python-2.7 pthreads gil

据我所知,Python 的线程库使用 POSIX 线程进行线程化,它不会在多核上运行。那么我们是否有可能使用 Open MP 为 Python 线程实现多核线程系统?

最佳答案

由于 Global Interpreter Lock,CPython(“默认”Python 实现)未使用多核.所以每个 Python 语句都必须持有该锁。

但用 C 编写的模块可能会在耗时操作之前释放解释器锁。 IE。 numpy 这样做:http://wiki.scipy.org/ParallelProgramming

他们有方便的例子:

import numpy as np
import math

def f(x):
    print x
    # This statements hold GIL and cannot be run
    # in two parallel threads 
    y = [1]*10000000
    [math.exp(i) for i in y]

def g(x):
    print x
    # This statements fall to NumPy C code
    # than release GIL and can be multithreaded
    y = np.ones(10000000)
    np.exp(y)

由于 OpenMP 也是 C 的工具,我认为这就是您所寻求的。

关于python - 使用多核在 Python 中进行线程化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29947994/

相关文章:

python - 如何组合两个函数,其外部函数为内部函数提供参数

python - 通过 event_generate 传递附加参数?

python - 如何使用smac进行卷积神经网络的超参数优化?

python - 如何创建python迭代器的副本?

python - 将文本文件转换为字典

python - 允许使用 token `class` 作为方法签名中的命名参数

python - writer.writeheader() - 无法识别在 header 中传递的字典的字段

c - 用pthread制作用户空间线程库,如何正确创建第一个线程? (前 2 个线程)

c - 哪个线程处理信号?

c - 是否有必要调用 pthread_join()