Python 中使用多核的线程

xen*_*ato 7 python pthreads gil python-2.7

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

mya*_*aut 6

由于Global Interpreter Lock的原因,CPython(“默认”Python 实现)未利用多核。因此每个 Python 语句都必须持有该锁。

但是用C编写的模块可能会在耗时的操作之前释放解释器锁。即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)
Run Code Online (Sandbox Code Playgroud)

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