什么是在Windows中复制fork()的最佳方式?

什么是在Windows中复制fork()的最佳方式?

问题描述:

如何实现一些逻辑,使我能够在Windows上重现Linux上的功能,并使用Python调用fork()系统调用?什么是在Windows中复制fork()的最佳方式?

我特别试图在SAPI Com组件上执行一个方法,同时在主线程中继续执行其他逻辑而不会阻塞或等待。

可能是一个版本的spawn()for python? http://en.wikipedia.org/wiki/Spawn_(operating_system)

+0

这就是`多处理`这些天在Windows上做的事情。 https://docs.python.org/3.5/library/multiprocessing.html?highlight=spawn#contexts-and-start-methods – clacke 2016-09-13 13:06:12

查看os module中的进程管理功能。有许多功能可以通过许多不同的方式启动新进程,包括同步和异步启动。

我还应该注意到Windows不提供与其他系统上的fork()完全相同的功能。要在Windows上执行多处理,您需要使用threading模块。

+8

`subprocess`和`multiprocessing`(由RJBrady建议)可能是更好的替代`os`和`线程`。 – jfs 2008-10-04 17:24:23

+1

`线程`不会在CPython中进行实际的多处理。 – clacke 2016-09-13 12:56:19

除了os模块格雷格指出,在这个过程中管理代码,你也应该看看线程模块:https://docs.python.org/library/threading.html

from threading import Thread 

def separate_computations(x, y): 
    print sum(x for i in range(y)) # really expensive multiplication 

Thread(target=separate_compuations, args=[57, 83]).start() 
print "I'm continuing while that other function runs in another thread!" 

你可能还喜欢使用处理模块(http://pypi.python.org/pypi/processing) 。它具有很多用于使用与线程模块相同的API编写并行系统的功能...

+1

从Python 2.6/3.0(2008年10月和12月)开始,`processing`就是`multiprocessing`的标准库的一部分。 – clacke 2016-09-13 13:01:14

来自Eli的线程示例将运行线程,但不会执行该线之后的任何工作。

我打算查看处理模块和子流程模块。我认为我运行的com方法需要在另一个进程中,而不是在另一个线程中。

+2

`multiprocessing`模块是标准库的一部分。 `subprocess`适合外部程序,``multiprocessing`适合python代码。 – jfs 2008-10-04 17:21:19

fork()已有实际上在Windows中重复,在Cygwin下,但它很毛茸茸。

Cygwin中的fork调用特别有趣,因为它在Win32 API上映射不好。这使得正确实施非常困难。

查看The Cygwin User's Guide了解这个黑客攻击的描述。

使用python multiprocessing module,它可以在任何地方工作。

这是一个IBM developerWords article,它演示了如何从os.fork()转换到多处理模块。