码迷,mamicode.com
首页 > 系统相关 > 详细

多进程调用

时间:2018-08-18 23:45:25      阅读:376      评论:0      收藏:0      [点我收藏+]

标签:time   返回   UNC   上下文环境   roc   完成   color   span   pid   

# 多进程调用(大部分与多线程的操作一样)
# 调用方式1
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=(alex,))
        p_list.append(p)
        p.start()
    for i in p_list:
        i.join()
    print(end)

# 调用方式2
from multiprocessing import Process
import time


class MyProcess(Process):
    # def __init__(self):
    #     super(MyProcess, self).__init__()
    #     self.name = name

    def run(self):
        time.sleep(1)
        print(hello, self.name, time.ctime())


if __name__ == __main__:
    p_list = []
    for i in range(3):
        p = MyProcess()
        # p.daemon = True   # 设置守护进程
        p.start()
        p_list.append(p)
    # for i in p_list:
    #     i.join()

    print(end...)


# 查看进程的pid
from multiprocessing import Process
import os, time


def info(title):
    print(title:, title)
    print(parent process:, os.getppid())
    print(process id:, os.getpid())


def f(name):
    info(function f)
    print(hello, name)


if __name__ == __main__:
    info(main process line)
    time.sleep(1)
    print(- * 30)
    p = Process(target=info, args=(alex,))
    p.start()
    p.join()

    # title: main process line
    # parent process: 1792      # 父进程的进程pid(pycharm)
    # process id: 4116      # 当前.py文件运行的pid
    # ------------------------------
    # title: alex
    # parent process: 4116      # 父进程的pid即当前.py文件运行的pid
    # process id: 6392      # 产生的子进程的pid

 

# Process类的方法与属性
# 构造方法:
# Process(group[, target[, name[, args[, kwargs]]]])
# group: 线程组,目前还没有实现,库引用中提示必须是None
# target: 要执行的方法
# name: 指定进程名
# args / kwargs: 要传入方法的参数
#
# 实例方法:
# is_alive() 返回进程是否在运行
# join([timeout]) 阻塞当前上下文环境的进程,直到调用此方法的进程终止或到达指定的timeout
# start() 进行准备就绪,等待cpu调度
# run() start()方法调用run方法,如果实例进程时未制定传入target,这start执行默认run方法
# terminate() 不管任务是否完成,立即停止工作进程
#
# 属性:
# daemon 和线程的setDaemon功能一样
# name 进程名字
# pid 进程号

from multiprocessing import Process
import time


class MyProcess(Process):
    def __init__(self, num):
        super(MyProcess, self).__init__()
        self.num = num

    def run(self):
        time.sleep(1)
        print(self.is_alive(), self.num, self.pid)
        time.sleep(1)


if __name__ == __main__:
    p_list = []
    for i in range(10):
        p = MyProcess(i)
        p_list.append(p)

    for p in p_list:
        p.start()

    print(main process end)

 

多进程调用

标签:time   返回   UNC   上下文环境   roc   完成   color   span   pid   

原文地址:https://www.cnblogs.com/dangrui0725/p/9499046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!