天天看点

Python多进程执行

from multiprocessing import Process
import time

def f_square(n):
    time.sleep()
    print n*n

if __name__=='__main__':
    for i in range():
        p = Process(target=f_square,args=[i,])
        p.start()
        print "p.pid:", p.pid
        print "p.name:", p.name
        print "p.is_alive:", p.is_alive()
           
p.pid: 109672
p.name: Process-1
p.is_alive: True
p.pid: 108304
p.name: Process-2
p.is_alive: True
p.pid: 110720
p.name: Process-3
p.is_alive: True
p.pid: 107916
p.name: Process-4
p.is_alive: True
p.pid: 106136
p.name: Process-5
p.is_alive: True
p.pid: 104820
p.name: Process-6
p.is_alive: True
p.pid: 113520
p.name: Process-7
p.is_alive: True
p.pid: 112672
p.name: Process-8
p.is_alive: True
p.pid: 113440
p.name: Process-9
p.is_alive: True
p.pid: 111076
p.name: Process-10
p.is_alive: True
           

要想让进程执行函数结果显示只能通过Python console运行.py文件才能打印出:0,1,4,9….的结果,这是Windows下Python多进程的一个问题。

更多关于多进程的操作参考这篇博文:https://www.cnblogs.com/kaituorensheng/p/4445418.html