如何产生一个进程

340 Visits / 0 Comments / Favorite

“产生”(spawn)的意思是,由父进程创建子进程。父进程既可以在产生子进程之后继续异步执行,也可以暂停等待子进程创建完成之后再继续执行。Python的multiprocessing库通过以下几步创建进程:

  1. 创建进程对象
  2. 调用 <span class="pre" style="box-sizing:border-box;">start()</span> 方法,开启进程的活动
  3. 调用 <span class="pre" style="box-sizing:border-box;">join()</span> 方法,在进程结束之前一直等待

2.1. 如何做…

下面的例子创建了5个进程,每一个进程都分配了 <span class="pre" style="box-sizing:border-box;">foo(i)</span> 函数, <span class="pre" style="box-sizing:border-box;">i</span> 表示进程的id:

# -*- coding: utf-8 -*-

import multiprocessing

def foo(i):
    print ('called function in process: %s' %i)
    return

if __name__ == '__main__':
    Process_jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=foo, args=(i,))
        Process_jobs.append(p)
        p.start()
        p.join()

执行本例需要打开命令行,到文件 <span class="pre" style="box-sizing:border-box;">spawn_a_process.py</span> (脚本名字)所在的目录下,然后输入下面的命令执行:

python spawn_a_process.py

我们会得到以下结果:

$ python process_2.py
called function in process: 0
called function in process: 1
called function in process: 2
called function in process: 3
called function in process: 4

All comments

Top