我在一个c#应用程序中成功地使用了pythonnet。现在,我尝试从parallel.for循环中调用pythonnet代码。
常规的for循环运行得很好,但使用并行时就不行了。程序没有响应,也没有显示错误消息。
(我也尝试了不同的方法,包括显式调用Py.GIL和使用线程。但无法使其运行)
以下是我的代码的简化版本:
static void Main(string[] args)
{
PythonEngine.Initialize();
dynamic np = PythonEngine.ImportModule("numpy");
dynamic[] Output = new dynamic[10];
dynamic[] Output2 = new dynamic[10];
for (int i = 0; i < 10; i++)
{
Output[i] = np.cos(np.pi * i);
}
Parallel.For(0, 10, i =>
{
Output2[i] = np.cos(np.pi * 2);
});
Console.ReadLine();
}发布于 2019-04-25 22:33:36
简而言之:(你的) Python是单线程的。
长长的答案:在谷歌上快速搜索PythonEngine.ImportModule,会得到relevant file in the github repo和np是一个PyObject。从同一目录中的pyobject.cs和runtime.cs文件中,我们可以看到调用np.cos是独立于线程的,除了指向外部Python库的PInvoke。在PythonNet项目页面http://pythonnet.github.io/中,它绑定到CPython。但是,CPython在解释器上有一个全局锁;请参阅Does Python support multithreading? Can it speed up execution time?。
可能的解决方案:如果你需要使用Python,尝试使用不同的运行时(例如IronPython,它是dotnet原生的)。
https://stackoverflow.com/questions/55848448
复制相似问题