本文实例讲述了Python使用multiprocessing创建进程的方法。分享给大家供大家参考。具体分析如下:
进程可以通过调用multiprocessing的Process进行创建,下面代码创建两个进程。
[root@localhost ~]# cat twoproces.py #!/usr/bin/env pythonfrom multiprocessing import Processimport osdef output(): print "My pid is :%d/n" % os.getpid() print "My parent is:%d/n" % os.getppid()def main(): p=Process(target=output) p.start() print "I am parent %d/n" % os.getpid()if __name__=="__main__": main()
运行结果如下:
[root@localhost ~]# ./twoproces.py I am parent 7656My pid is :7660My parent is:7656
以下程序结果的mypid值将在两个进程中固定不变.
[root@localhost ~]# cat badprocessID.py #!/usr/bin/env pythonfrom multiprocessing import Processimport osdef output(mypid): print "I am child %d ID :%d/n" % (os.getpid(),mypid)def main(): mypid=os.getpid() p=Process(target=output,args=(mypid,)) print "I am parent %d/n" % os.getpid() p.start()if __name__=="__main__": main()
有与子进程并没有重设mypid,所以运行过程中mypid并没有任何改变。
下面代码将创建一个由子进程创建子进程的进程链。
[root@localhost ~]# cat simplechina.py #!/usr/bin/env pythonimport osfrom multiprocessing import Processdef output(howmany,childpid): info = (howmany,os.getpid(),os.getppid(),childpid) print "i:%d process ID:%d parent ID%d child ID %d/n" % infodef chain(howmany): howmany = howmany-1 if howmany > 0: p = Process(target=chain,args=(howmany,)) p.start() output(howmany,p.pid)def main(): childpid = 0 howmany=6 p = Process(target=chain,args=(howmany,)) p.start()if __name__=="__main__": main()
有与主进程利用Process创建子进程,而子进程又再创建子进程(也就是A->B->C-D),如此类推,知道howmany小于0结束。运行1结果如下:
[root@localhost ~]# ./simplechina.py i:5 process ID:13581 parent ID13580 child ID 13582i:4 process ID:13582 parent ID13581 child ID 13583i:3 process ID:13583 parent ID13582 child ID 13584i:2 process ID:13584 parent ID13583 child ID 13585i:1 process ID:13585 parent ID13584 child ID 13586
接下来如何创建一个进程扇,也就是:
A
/ /
B C
建立simplefan.py文件,代码如下:
[root@localhost ~]# cat simplefan.py #!/usr/bin/env pythonimport osfrom multiprocessing import Processdef output(howmany,childpid): info = (howmany,os.getpid(),os.getppid(),childpid) print "i:%d process ID:%d parent ID%d child ID %d/n" % infodef fan(i): output(i,os.getpid())def main(): pList=[] for i in range(6): p = Process(target=fan,args=(i,)) pList.append(p) for p in pList: p.start() for p in pList: p.join()if __name__=="__main__": main()
新闻热点
疑难解答