【发布时间】:2017-10-02 04:33:51
【问题描述】:
我编写了一个 Python 脚本,该脚本调用了一个使用 OpenMP 并行化的 C 函数(从 Python 到 C 函数的变量是使用 ctypes-wrapper 传递的)。 C 函数正常工作,产生所需的输出。但是我在 Python 代码的末尾遇到了分段错误。我怀疑它与 OpenMP 产生的线程有关,因为禁用 OpenMP 时不会发生 seg-fault。
在代码的 Python 端(调用外部 C 函数)我有:
...
C_Func = ctypes.cdll.LoadLibrary ('./Cinterface.so')
C_Func.Receive_Parameters.argtypes = (...list of ctypes variable-type ...)
C_Func.Receive_Parameters.restype = ctypes.c_void_p
C_Func.Perform_Calculation.argtypes = ( )
C_Func.Perform_Calculation.restypes = ctypes.c_void_p
在 C 端,函数的通用形式是:
void Receive_Parameters (....list of c variable-type ...)
{
---Take all data and parameters coming from python---
return;
}
void Perform_Calculation ( )
{
#pragma omp parallel default(shared) num_threads(8) private (....)
{
#pragma omp for schedule (static, 1) reduction (+:p)
p+= core_calculation (...list of variables....)
}
return;
}
float core_calculation (...list of variables...)
{
----all calculations done here-----
}
我有以下问题和相关的困惑:
Python 对 C 函数内部的 OpenMP 产生的线程的操作有任何控制吗?我问这个的原因是 C 函数接收指向由 Python 在堆中分配的数组的指针。 OpenMP 线程能否在不关心分配位置的情况下并行执行此数组的操作?
在调用 C 函数之前我是否需要在 Python 代码中执行任何操作,比如释放 GIL 以允许在 C 函数中生成 OpenMP 线程?如果是,如何做到这一点?
我必须在 C 函数中释放 GIL(在 OpenMP 并行块之前)吗?
【问题讨论】:
-
忘了添加,C 函数将指针指向在 python 中分配的数组。只是想知道这是否可能是段错误的原因之一。
-
您忘记添加minimal reproducible example(请仔细阅读该页面)。如果没有特定的代码来重现它,推测你的错误是没有用的。
-
抱歉,代码太长,无法在此发布。我已经提出了一些疑问,我认为这可能是我看到的段错误的原因。
标签: python c multithreading segmentation-fault openmp