如何在python中一个接一个地运行两个进程



我正在尝试运行两个命令,一个接一个。我的代码看起来像:

baking.bake()
print "baking completed"

我的目标是运行baking.bake()(大约需要1分钟才能完成),然后立即想要打印"烘焙开始"。最后,当烘焙完成后,我想打印"烘焙完成"。本质上:我如何异步运行bake() ?

这是我的back .py文件

# Bake a texture map
from cgkit.cmds import load, worldObject, listWorld
from cgkit.rmshader import RMMaterial, RMShader
from cgkit.sceneglobals import Globals

def bake():
        Globals(
            bake = True,
            resolution = (512, 512),
            pixelsamples = (2,2),
            output = "ao_map.tif",
            displaymode = "rgba"
        )
        # Load the model
        load("singleSofa.obj")
        # Obtain a reference to the model
        model = worldObject("small_sofa_dark_grey")
        # Set the bake material
        mat = RMMaterial(
            surface = RMShader(
                "bake_ao.sl",
                samples = 1000,
            )
        )
        model.setMaterial(mat)

您可以使用多处理模块,如下所示:

from multiprocessing import Pool
import time
def something(i):
    time.sleep(2)
    return i+i
pool = Pool(processes=1)
res = pool.apply_async(something, [2])
print "Started something, waiting..."
# ...
print "Done with something. Result was: %s" % (res.get())

那么在你的场景中我们可以这样做:

from multiprocessing import Pool
# Create baking object and so forth.
# ...
pool = Pool(processes=1)
res = pool.apply_async(baking.bake)
print "Baking started"
# Then we do something while we wait...
res.get()
print "Baking done."

基本上您将使用threading模块及其join方法:

import threading    
def print_hello():
    for _ in range(3):
        print 'Hello'
hello_thread = threading.Thread(target=print_hello)
hello_thread.start()
hello_thread.join()
print "We're done!"

这段代码将打印:

你好

你好

你好

做完了!

在你的例子中,你将创建一个线程:

bake_thread = threading.Thread(target=baking.bake)

然后简单地start线程和join与它。

相关内容

  • 没有找到相关文章

最新更新