#带参数的进程函数演示
from multiprocessing import Process
from time import sleep
#带参数的进程函数
def worker(sec,name):
for i in range(3):
sleep(sec)
print("I'm %s"%name)
print("I'm working...")
p = Process(target = worker,args =(2,),\
kwargs = {'name' : 'zhang'},name = "Worker") # 注意传递元组只有一个变量需要加逗号
p.start()
print(p.name)
print(p.pid)
#进程alive情况
print('Process is alive:',p.is_alive())
p.join()
演示daemon
#演示daemon属性
from multiprocessing import Process
from time import sleep,ctime
def tm():
while True:
sleep(2)
print(ctime())
p = Process(target = tm)
#设置属性都要在start之前完成
p.daemon = True # 子进程伴随着主进程结束,不和join一同使用
p.start()
sleep(5)
print('main process exit')
#自定义进程类,简单实现时钟打印功能
from multiprocessing import Process
import time
class ClockProcess(Process):
def __init__(self,value):
self.value = value
super().__init__()
#重写run方法
def run(self):
for i in range(5):
print('The time is {}'.\
format(time.ctime()))
time.sleep(self.value)
#创建自定义进程类的对象
p = ClockProcess(2)
#自动调用run
p.start()
p.join()