我目前正在寻求使用多处理的能力来加速我的代码.然而,在从python调用编译后的代码时,我遇到了一些问题,因为当编译后的文件包含任何形式的多处理时,编译后的文件似乎会从代码的视图中消失.

例如,使用以下测试代码:

#include <omp.h>

int main() {
    int thread_id;
#pragma omp parallel
    {
        thread_id = omp_get_thread_num();
    }
    return 0;
}

在这里,我编译程序,然后使用以下命令将其转换为.so文件

gcc -fopenmp -o theories/test.so -shared -fPIC -O2 test.c

然后,我try 从test.py运行上述代码:

from ctypes import CDLL
import os

absolute_path = os.path.dirname(os.path.abspath(__file__))
# imports the c libraries
test_lib_path = absolute_path + '/theories/test.so'
test = CDLL(test_lib_path)
test.main()
print('complete')

我得到以下错误:

FileNotFoundError: Could not find module 'C:\[my path]\theories\test.so' (or one of its dependencies). Try using the full path with constructor syntax.

但是,当我注释掉多处理元素以获得以下代码时:

#include <omp.h>

int main() {
    int thread_id;
    /*
#pragma omp parallel
    {
        thread_id = omp_get_thread_num();
    }
    */
    return 0;
}

然后,我可以完美地执行,并在最后打印出"Complete".

我想知道这是怎么发生的,为什么代码看起来编译得很好,但只有在从Python调用它之后才会引发问题(我也判断了一下,文件实际上已经创建了).

最新情况:

  1. 我现在已经判断了我是否安装了libgomp-1.dll
  2. 我已经卸载并重新安装了MinGW,没有发生任何变化.
  3. 我安装了不同的64位版本的GCC,并且使用不同的(64位的python3.10)版本的python会重现相同的错误.这里还有libgomp-1.dll.

推荐答案

我认为这有same root cause作为[SO]: Can't import dll module in Python (@CristiFati's answer)(也判断[SO]: PyWin32 and Python 3.8.0 (@CristiFati's answer)).

A .dll (.so) is only loaded when its dependencies are successfully loaded (recursively).
[SO]: Python Ctypes - loading dll throws OSError: [WinError 193] %1 is not a valid Win32 application (@CristiFati's answer) focuses on a different error, but covers this topic.

当注释掉omp_get_thread_num调用时,链接器不再将test.so链接到libgomp*.dll(因为它不需要其中的任何内容),并且代码运行得很好(所有需要的.dll都找到了).

要解决该问题,您应该添加到100(在try 加载.so之前):

  1. libgomp*.dll的目录

  2. MinGWbin目录

  3. 可能包含所需的.dll的任何其他目录(从属)

要查看.dll个依赖项,请选中[SO]: Discover missing module using command-line ("DLL load failed" error) (@CristiFati's answer).

Notes:

Python相关问答推荐

有症状地 destruct 了Python中的regex?

在线条上绘制表面

如何使用Python以编程方式判断和检索Angular网站的动态内容?

Pandas DataFrame中行之间的差异

计算每个IP的平均值

Pandas—在数据透视表中占总数的百分比

移动条情节旁边的半小提琴情节在海运

如何在UserSerializer中添加显式字段?

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

需要帮助重新调整python fill_between与数据点

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

如何使用两个关键函数来排序一个多索引框架?

如何在海上配对图中使某些标记周围的黑色边框

如果包含特定值,则筛选Groupby

为什么t sns.barplot图例不显示所有值?'

分解polars DataFrame列而不重复其他列值

一维不匹配两个数组上的广义ufunc

try 在单个WITH_COLUMNS_SEQ操作中链接表达式时,使用Polars数据帧时出现ComputeError

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)

是否将列表分割为2?