其他分享
首页 > 其他分享> > 线程_Process实例

线程_Process实例

作者:互联网

from multiprocessing import Process
import os
from time import sleep

def run_proc(name,age,**kwargs):

    for i in range(10):
        print("子进程运行中,名字为 = %s,年龄为 = %d,子进程 = %d..."%(name,age,os.getpid()))
        print(kwargs)
        sleep(0.5)

if __name__ == '__main__':

    print("父进程: %d"%(os.getpid()))
    pro = Process(target=run_proc,args=('test',18),kwargs={'kwargs':20})
    print("子进程将要执行")
    pro.start( )
    sleep(1)
    pro.terminate()#将进程进行终止
    pro.join()
    print("子进程已结束")

from multiprocessing import Process
import time
import os

#两个子进程将会调用的两个方法
def work_1(interval):

    # intercal为挂起时间
    print("work_1,父进程(%s),当前进程(%s)"%(os.getppid(),os.getpid()))
    start_time = time.time()
    time.sleep(interval)
    end_time = time.time()
    print("work_1,执行时间为%f"%(end_time-start_time))

def work_2(interval):

    print("work_2,父进程(%s),当前进程(%s)"%(os.getppid(),os.getpid()))
    start_time = time.time()
    time.sleep(2)
    end_time = time.time()
    print("work_2执行时间为:%.2f"%(end_time-start_time))

if __name__ == '__main__':

    print("进程Id:", os.getpid())
    pro1 = Process(target=work_1, args=(2,))
    pro2 = Process(target=work_2, name="pro2", args=(3,))
    pro1.start()
    pro2.start()
    print("pro2.is_alive:%s" % (pro2.is_alive()))
    print("pro1.name:", pro1.name)
    print("pro1.pid=%s" % pro1.pid)
    print("pro2.name=%s" % pro2.name)
    print("pro2.pid=%s" % pro2.pid)
    pro1.join()
    print("pro1.is_alive:", pro1.is_alive())

2020-05-07

标签:name,Process,pro2,pro1,实例,线程,time,print,os
来源: https://www.cnblogs.com/hany-postq473111315/p/12845545.html