Python 中fork()理解

参考:多进程- 廖雪峰的官方网站
首先,在python中我们要实现多进程,有两个模块可以用:
1)os中的fork()函数
2)multiprocessing模块
那么这两个模块有什么区别呢?
在fork()是基于unix/linux内核的函数,在windows中无法使用,因此multiprocessing模块作为跨平台的存在。

fork()

作为例子,我们先把参考博客中的例子拿过来

# multiprocessing.py
import os
print 'Process (%s) start...' % os.getpid()
pid = os.fork()
if pid==0:
	print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())
else:
	print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)

os.fork()这个函数,对于父进程,返回的是子进程的pid,对于子进程,返回的是0. 而通过os.getpid()得到的是当前的pid,os.getppid()得到的是父进程的pid。

更进一步的分析:

# multiprocessing.py
import os
print 'Process (%s) start...' % os.getpid()
fork_num = 0
while(fork_num < 3):
    pid = os.fork()
    fork_num += 1
    if pid==0:
        print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())
    else:
        print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)

在运行之前,我们分析可以得到,经过三次循环,应该有8个进程
运行结果:

Process (427) start...
I (427) just created a child process (428).
I (427) just created a child process (429).
I am child process (428) and my parent is 427.
I (427) just created a child process (430).
I (428) just created a child process (431).
I am child process (431) and my parent is 428.
I (428) just created a child process (432).
I (431) just created a child process (433).
I am child process (433) and my parent is 431.
I am child process (430) and my parent is 427.
I am child process (429) and my parent is 427.
I am child process (432) and my parent is 428.
I (429) just created a child process (434).
I am child process (434) and my parent is 429.

该函数在运行时,是将代码在子进程中复制了一份

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值