python 多进程

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 01:52   28   0
from multiprocessing import Process
import time

def f(name):
    time.sleep(1)
    print("hello",name,time.ctime())
if __name__ == '__main__':
    p_list=[]
    for i in range(3):
        p=Process(target=f,args=('alvin',))
        p_list.append(p)
        #p.daemon=True
        p.start()

    print('end....')

多进程模式:是由一个主进程创建多个其他进程,因此其他进程的父进程就是这个主进程

####eg1:
from multiprocessing import Process
import time,os

def f(name):

    print("hello",name)
    print('parent process:' , os.getppid())
    print('process:',os.getpid())
if __name__ == '__main__':
    p_list=[]
    for i in range(3):
        p=Process(target=f,args=('alvin',))
        p_list.append(p)
        #p.daemon=True
        p.start()
###执行结果####

hello alvin
parent process: 20308
process: 19656
hello alvin
parent process: 20308
process: 5688
hello alvin
parent process: 20308
process: 9344

#######eg2###########
from multiprocessing import Process
import time,os

def info(title):
    print('title:',title)
    print('parent process:' , os.getppid())
    print('process:',os.getpid())
def f(name):
    info('function f')
    print("hello",name)

if __name__ == '__main__':
    info('main process line')
    time.sleep(1)
    p=Process(target=info,args=('alvin',))
    p.start()

###执行结果####

title: main process line
parent process: 1644
process: 15848
title: alvin
parent process: 15848
process: 3348

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP