c# - 如何在 Windows 上使用 Python for .NET 进行多处理?

标签 c# python windows multiprocessing python.net

现在我正在开发在 Windows 上运行的 C# 应用程序。 一些进程是用 Python 编写的,通过 pythonnet(Python for .NET)调用。 这些过程计算量大,所以我想并行进行。

它们受 CPU 限制,可以独立处理。

据我所知,有两种可能的实现方式:

  1. 启动多个 Python 运行时
    第一种方法是启动多个 Python 解释器,但似乎不可行。 因为 pythonnet 显然只能管理一个由静态方法初始化的解释器,PythonEngine.Initialize()。
    From the Python.NET documentation:

    Important Note for embedders: Python is not free-threaded and uses a global interpreter lock to allow multi-threaded applications to interact safely with the Python interpreter. Much more information about this is available in the Python C-API documentation on the www.python.org Website.
    When embedding Python in a managed application, you have to manage the GIL in just the same way you would when embedding Python in a C or C++ application.
    Before interacting with any of the objects or APIs provided by the Python.Runtime namespace, calling code must have acquired the Python global interpreter lock by calling the PythonEngine.AcquireLock method. The only exception to this rule is the PythonEngine.Initialize method, which may be called at startup without having acquired the GIL.

  2. 在 Python 中使用多处理包
    另一种方法是使用多处理包。 根据 Python 文档,如果代码在 Windows 上运行以确保生成有限进程,则需要以下语句:
    如果 __name__ == "__main__":
    然而,用Python编写的函数被作为模块的一部分,因为它嵌入到.NET中。
    例如,以下代码是可执行的,但会无限生成进程。

//C#
static void Main(string[] args)
    {
        using (Py.GIL())
        {
            PythonEngine.Exec(
                "print(__name__)\n" + //output is "buitlins"
                "if __name__ == 'builtins':\n" +
                "   import test_package\n" +  //import Python code below
                "   test_package.async_test()\n"
                );
        }
    }
# Python
import concurrent.futures

def heavy_calc(x):
    for i in range(int(1e7) * x):
        i*2

def async_test():
    # multiprocessing
    with concurrent.futures.ProcessPoolExecutor(max_workers=8) as executor:
        futures = [executor.submit(heavy_calc,x) for x in range(10)]
        (done, notdone) = concurrent.futures.wait(futures)
        for future in futures:
            print(future.result())

有解决上述问题的好办法吗? 如有任何意见,我们将不胜感激。提前致谢。

最佳答案

对于每个 python 调用, 1.创建一个appDomain 2. 在 appdomain 中创建一个异步运行 python 的任务。

因为它是独立的 AppDomains,静态方法将是独立的。

创建一个使用 AppDomain 的任务很繁重,所以如果您的调用数量非常大,我就无法做到这一点,但听起来您可能只有少量进程要异步运行。

关于c# - 如何在 Windows 上使用 Python for .NET 进行多处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47978171/

相关文章:

c# - 相同的GetHashCode()用于不同的对象

c# - 如何从终结器中正确处理非托管资源的集合?

windows - 设置我们的新开发服务器 分配多个 IP 地址的最简单方法是什么

python - 如何在 python 中使用带有代理身份验证的 requests.post()?

linux - MenuItem 位图引发断言失败……

c# - 自动鼠标点击屏幕

c# - 出于安全原因,弹出窗口不能隐藏在屏幕边缘

c# - 将数据存储在程序中或文档文件中有区别吗?

Python 可写缓冲区/memoryview 到数组/bytearray/ctypes 字符串缓冲区

python - Spacy NLP 库 : what is maximum reasonable document size