multiprocess-Process-Pool-Queue-2017-6-8

<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org3e98343">1. .os.fork() 子进程接受返回值 0,父进程接受返回值是子进程的 pid</a></li>
<li><a href="#orge45d9ce">2. 多进程每个变量各拥有一份,互不影响</a></li>
<li><a href="#orgcca67d6">3. 多次 fork()</a></li>
<li><a href="#orge18a284">4. multiprocessing 模块</a></li>
<li><a href="#orgb98fd3a">5. Process 子类</a></li>
<li><a href="#org2c79c73">6. 进程池 Pool</a></li>
<li><a href="#org795128d">7. Queue 的表现</a></li>
</ul>
</div>
</div>

<a id="org3e98343"></a>

.os.fork() 子进程接受返回值 0,父进程接受返回值是子进程的 pid

import os
rpid = os.fork()
if rpid<0:
    print("failed to fork")
elif rpid==0:
    print("I am the son process (%s),my parent process is (%s)"%(os.getpid(),os.getpid()))
else:
    print("i am parent process (%s),my son process is (%s)"%(os.getpid(),rpid))
print("will be run by son and parent")

In [4]: %run test5.py
i am parent process (24829),my son process is (25083)
will be run by son and parent
I am the son process (25083),my parent process is (25083)
will be run by son and parent
这种情况在 ipython 下创建了两个进程抢输入,没救

<a id="orge45d9ce"></a>

多进程每个变量各拥有一份,互不影响

import os
rpid = os.fork()

n1=5
if rpid<0:
    print("failed to fork")
elif rpid==0:
    g,n=1,2
    print("I am the son process (%s),my parent process is (%s)"%(os.getpid(),os.getpid()))
    print(locals())
    print(globals())
    n1=6
    print(locals())
    print(globals())
else:
    g,n=3,6
    time.sleep(4)
    print("father sleep 4s,let son pass first!")
    print("i am parent process (%s),my son process is (%s)"%(os.getpid(),rpid))
    print(locals())
    print(globals())
print("will be run by son and parent")

---------------------------------------------------–—结果
I am the son process (25938),my parent process is (25938)
I am the son process (25938),my parent process is (25938)
{'g': 1, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 0, 'n1': 5, 'time': <module 'time' (built-in)>, 'name': $
{'g': 1, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 0, 'n1': 5, 'time': <module 'time' (built-in)>, 'name': $
{'g': 1, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 0, 'n1': 6, 'time': <module 'time' (built-in)>, 'name': $
{'g': 1, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 0, 'n1': 6, 'time': <module 'time' (built-in)>, 'name': $
will be run by son and parent
father sleep 4s,let son pass first!
i am parent process (25937),my son process is (25938)
{'g': 3, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 25938, 'n1': 5, 'time': <module 'time' (built-in)>, '_name$
{'g': 3, 'builtins': <module 'builtin' (built-in)>, 'file': 'test5.py', 'package': None, 'rpid': 25938, 'n1': 5, 'time': <module 'time' (built-in)>, '_name$
will be run by son and parent

<a id="orgcca67d6"></a>

多次 fork()

import os
import time
pid = os.fork()
if pid == 0:
    print("haha 1 %s"%(os.getpid()))
else:
    print("hehe 2 %s"%(os.getpid()))
pid = os.fork()
if pid==0:
    print("haha 3 %s %s"%(os.getpid(),os.getppid()))
else:
    print("haha 4 %s %s"%(os.getpid(),os.getppid()))
time.sleep(1)

---------------------------------------------------------–—结果
hehe 2 26877
haha 1 26878
haha 4 26877 25179
haha 4 26878 26877
haha 3 26880 26878
haha 3 26879 26877

2 与 1 分别执行一次,接下来 26878 走一遍 4,并产生一个子进程执行 3.26877 执行 4
并产生一个子进程执行 3。

<a id="orge18a284"></a>

multiprocessing 模块

Process 的 target 不仅可以传递函数,也可以传递绑定方法,也可以传递类

from  multiprocessing import Process
import os
from time import sleep
import types
def run_proc(jj,name,age,**kwargs):
    for i in range(10):
        print("son process running,name=%s,age=%di,pid=%d..."%(name,age,os.getpid()))
        print(kwargs)
        sleep(0.5)

class A:
    pass

A.run_proc=types.MethodType(run_proc,A)
a=A()
#a.run_proc(18,m=12,t=13)

if __name__=='__main__':
    print('parent process is %d'%os.getpid())
    p=Process(target=run_proc,args=(a,'hi',18,),kwargs={"m":20})
    print("son process will running")
    p.start()
    sleep(1)
    p.terminate()
    p.join()
    print("son process have end")

from  multiprocessing import Process
import os
from time import sleep
import types

class A:
    def __init__(self,name,age,**kwargs):
        for i in range(10):
            print("son process running,name=%s,age=%di,pid=%d..."%(name,age,os.getpid()))
            print(kwargs)
            sleep(0.5)
    pass


#a.run_proc(18,m=12,t=13)

if __name__=='__main__':
    print('parent process is %d'%os.getpid())
    p=Process(target=A,args=('hi',18),kwargs={"m":20})
    print("son process will running")
    p.start()
    sleep(1)
    p.terminate()
    p.join()
    print("son process have end") 

<a id="orgb98fd3a"></a>

Process 子类

from multiprocessing import Process
import time
import os

class Process_Class(Process):
    def __init__(self,interval):
        Process.__init__(self)
        self.interval = interval
    def run(self):
        print("son process (%s)start running,parent process is (%s)"%(os.getpid(),os.getppid()))
        t_start = time.time()
        time.sleep(self.interval)
        t_stop = time.time()
        print("(%s)end ..,elapsed(%0.2f)s"%(os.getpid(),t_stop-t_start))

if __name__=='__main__':
    t_start=time.time()
    print("present process is (%s)"%os.getpid())
    p1 = Process_Class(2)
    p1.start()
    p1.join()
    t_stop = time.time()
    print("(%s)end...,elapsed (%0.2f)"%(os.getpid(),t_stop-t_start))

present process is (11503)
son process (29364)start running,parent process is (11503)
(29364)end ..,elapsed(2.00)s
(11503)end…,elapsed (2.01)

<a id="org2c79c73"></a>

进程池 Pool

from multiprocessing import Pool
import os,time,random

def worker(msg):
    t_start=time.time()
    print("%s start run,pid is %d"%(msg,os.getpid()))
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg,"end run.elapsed time is %0.2f"%(t_stop-t_start))

po=Pool(3)
for i in range(0,10):
    po.apply_async(worker,(i,))

print("-----start------")
po.close()
po.join()
print("----end-----")

0 start run,pid is 29668
2 start run,pid is 29670
1 start run,pid is 29669
–—start-–—
2 end run.elapsed time is 0.64
3 start run,pid is 29670
3 end run.elapsed time is 0.31
4 start run,pid is 29670
4 end run.elapsed time is 0.14
5 start run,pid is 29670
0 end run.elapsed time is 1.16
6 start run,pid is 29668
5 end run.elapsed time is 0.73
7 start run,pid is 29670
1 end run.elapsed time is 1.92
8 start run,pid is 29669
6 end run.elapsed time is 0.96
9 start run,pid is 29668
7 end run.elapsed time is 0.92
8 end run.elapsed time is 1.82
9 end run.elapsed time is 1.73
-—end–—

<a id="org795128d"></a>

Queue 的表现

from multiprocessing import Queue
q=Queue(3) 
q.put("msg1")
q.put("msg2")
print(q.full())  #False
q.put("msg3")
print(q.full()) #True
try:
    q.put("msg4",True,2)
except:
    print("msg queue is full,now the num is:%s"%q.qsize())
try:
    q.put_nowait("msg4")
except:
    print("msg queue is full,the num is:%s"%q.qsize())
if not q.full():
    q.put_nowait("mag4")
if not q.empty():
    for i in range(q.qsize()):
        print(q.get_nowait()) 

False
True
msg queue is full,now the num is:3
msg queue is full,the num is:3
msg1
msg2
msg3

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,227评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,755评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,899评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,257评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,617评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,757评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,982评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,715评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,454评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,666评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,148评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,512评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,156评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,112评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,896评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,809评论 2 279
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,691评论 2 272

推荐阅读更多精彩内容

  • 历经十一载,上南少林!今终上顶一览!!
    那些年8713阅读 229评论 0 0
  • 鸡汤文学兴起于20世纪上半叶,那个时候,经济不景气、不平等、战争等恶魔正在磨灭人类追求美好生活的心灵,所以出...
    静斋先生阅读 577评论 1 2
  • 小木还是像个小姑娘一样猫着腰,垫着步小跑着过来,脸颊红扑扑的,一把拉开椅子,坐下,看着三山脸上五年前留下的疤,语气...
    李小鹿儿阅读 390评论 0 0
  • 文/葱葱 我的眼睛里有发烧的物件 我的梦境里有断翅的蝴蝶 我的思想里有焦灼的蚂蚁 我的身子里有骄傲的氢气 日子被雨...
    葱葱_阅读 454评论 31 30