Skip to main content
 首页 » 编程设计

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

2024年10月25日12daizhj

据我所知,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 的工具,我认为这就是您所寻求的。