简体   繁体   English

运行同时嵌入C ++的python脚本

[英]Run python scripts concurrently embedded in C++

Is it possible to run scripts ie. 是否有可能运行脚本即。 with PyRun_SimpleFile() in separate C++ threads so they run concurrently? 在单独的C ++线程中使用PyRun_SimpleFile()使它们同时运行?

I suspect no because of the GIL. 我怀疑不是因为GIL。 But if there is any kind of trick making it possible please tell. 但是,如果有任何技巧可以实现,请告诉。

Best Regards Jakob 最好的问候雅各布

You can run them concurrently, but the GIL prevents them from running in parallel and utilizing your multiple CPU cores fully. 您可以同时运行它们,但是GIL阻止它们并行运行并充分利用多个CPU内核。 This can be good enough if you mostly dispatch to other long running C++/CUDA code that releases the GIL again and if you only have a few CPUs. 如果您主要调度到其他长时间运行的C ++ / CUDA代码,而这些代码又会释放GIL,并且您只有几个CPU,那么这可能就足够了。

This would be the approach taken by Sub-Interpreters , multiple mostly independent python interpreters that share only some parts, but sadly this includes the GIL, so it brings no benefits for parallel processing, and only small benefits for isolation between concurrently running scrips. 这将是Sub-Interpreters所采用的方法, Sub-Interpreters是仅共享某些部分的多个主要独立的python解释器,但可悲的是,其中包括GIL,因此它对并行处理没有好处,而在并发运行的脚本之间的隔离也没有什么好处。 One example of this approach is mod_wsgi . 这种方法的一个示例是mod_wsgi

Sub interpreters are a rarely used feature, so expect weird bugs/race conditions in C extensions that don't expect them. 子解释器是一个很少使用的功能,因此请期待C扩展中不期望它们的怪异错误/竞争条件。

If you said C# or Java instead of C++, you could use IronPython or Jython, to achieve your goal, as those do not have a GIL. 如果您说的是C#或Java而不是C ++,则可以使用IronPython或Jython来实现您的目标,因为那些没有GIL。

With CPython you can only do safely what multiprocessing does. 使用CPython,您只能安全地执行多处理功能。 The multiprocessing modul sidesteps the design issues of the GIL and just starts an extra process, but if you have expensive shared memory structures and no fork() syscall, this fails to deliver. 多重处理模块回避了GIL的设计问题,并开始了一个额外的过程,但是,如果您拥有昂贵的共享内存结构并且没有fork()syscall,则此操作无法实现。

Of course, if you start to hack on the python implementation itself, you might be able to isolate all global state into a smaller contexts. 当然,如果您开始研究python实现本身,则可以将所有全局状态隔离到较小的上下文中。 But if you do that, you might as well just use a language that is designed for this multi-threaded embedding usecase like Tcl (look at NaviServer or F5s irules ) or Lua . 但是,如果这样做,您也可能只使用为这种多线程嵌入用例设计的语言,例如Tcl (请看NaviServer或F5s irules )或Lua

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM