美文网首页
Python多任务-进程

Python多任务-进程

作者: 莫忘初心_倒霉熊 | 来源:发表于2020-02-21 16:46 被阅读0次

进程的创建-multiprocessing

multiprocessing模块就是跨平台版本的多进程模块,提供了一个Process类来代表一个进程对象,这个对象可以理解为是一个独立的进程,可以执行另外的事情

# -*- coding:utf-8 -*-
from multiprocessing import Process
import time

def run_proc():
   """子进程要执行的代码"""
   while True:
       print("----2----")
       time.sleep(1)

if __name__=='__main__':
   p = Process(target=run_proc)
   p.start()
   while True:
       print("----1----")
       time.sleep(1)

创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动

进程pid

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time

def run_proc():
    """子进程要执行的代码"""
    print('子进程运行中,pid=%d...' % os.getpid())  # os.getpid获取当前进程的进程号
    print('子进程将要结束...')

if __name__ == '__main__':
    print('父进程pid: %d' % os.getpid())  # os.getpid获取当前进程的进程号
    p = Process(target=run_proc)
    p.start()

Process语法结构如下:

  1. Process([group [, target [, name [, args [, kwargs]]]]])
  • target:如果传递了函数的引用,可以任务这个子进程就执行这里的代码
  • args:给target指定的函数传递的参数,以元组的方式传递
  • kwargs:给target指定的函数传递命名参数
  • name:给进程设定一个名字,可以不设定
  • group:指定进程组,大多数情况下用不到
  1. Process创建的实例对象的常用方法:
  • start():启动子进程实例(创建子进程)
  • is_alive():判断进程子进程是否还在活着
  • join([timeout]):是否等待子进程执行结束,或等待多少秒
  • terminate():不管任务是否完成,立即终止子进程
  1. Process创建的实例对象的常用属性:
  • name:当前进程的别名,默认为Process-N,N为从1开始递增的整数
  • pid:当前进程的pid(进程号)

给子进程指定的函数传递参数

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
from time import sleep


def run_proc(name, age, **kwargs):
    for i in range(10):
        print('子进程运行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid()))
        print(kwargs)
        sleep(0.2)

if __name__=='__main__':
    p = Process(target=run_proc, args=('test',18), kwargs={"m":20})
    p.start()
    sleep(1)  # 1秒中之后,立即结束子进程
    p.terminate()
    p.join()
运行结果:

子进程运行中,name= test,age=18 ,pid=45097...
{'m': 20}
子进程运行中,name= test,age=18 ,pid=45097...
{'m': 20}
子进程运行中,name= test,age=18 ,pid=45097...
{'m': 20}
子进程运行中,name= test,age=18 ,pid=45097...
{'m': 20}
子进程运行中,name= test,age=18 ,pid=45097...
{'m': 20}

进程间不同享全局变量

# -*- coding:utf-8 -*-
from multiprocessing import Process
import os
import time

nums = [11, 22]

def work1():
    """子进程要执行的代码"""
    print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
    for i in range(3):
        nums.append(i)
        time.sleep(1)
        print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))

def work2():
    """子进程要执行的代码"""
    print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))

if __name__ == '__main__':
    p1 = Process(target=work1)
    p1.start()
    p1.join()

    p2 = Process(target=work2)
    p2.start()
运行结果:

in process1 pid=11349 ,nums=[11, 22]
in process1 pid=11349 ,nums=[11, 22, 0]
in process1 pid=11349 ,nums=[11, 22, 0, 1]
in process1 pid=11349 ,nums=[11, 22, 0, 1, 2]
in process2 pid=11350 ,nums=[11, 22]

进程间通信-Queue

可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Queue本身是一个消息列队程序。

我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    while True:
        if not q.empty():
            value = q.get(True)
            print('Get %s from queue.' % value)
            time.sleep(random.random())
        else:
            break

if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()    
    # 等待pw结束:
    pw.join()
    # 启动子进程pr,读取:
    pr.start()
    pr.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    print('')
    print('所有数据都写入并且读完')

"""
输入如下:
Put A to queue...
Put B to queue...
Put C to queue...
Get A from queue.
Get B from queue.
Get C from queue.

所有数据都写入并且读完
"""

相关文章

  • Python多线程多进程

    Python多线程多进程 QUICK START 1.[endif]进程和线程 1.1系统多任务机制 多任务操作的...

  • 2018-11-22进程,线程,协程

    进程:代码+资源,可以实现多任务线程:运行在进程中的最小单元,消耗资源小于进程 可以实现多任务协程:Python独...

  • Python3简单实现多任务(线程/协程篇)

    写在前面 上一篇文章[Python3简单实现多任务(多进程篇)]已经介绍了python多进程实现多任务的简单实现方...

  • 黑马上海37期Python全套视频课程

    教程目录:┣━Python就业班 ┃┣━02 多任务 ┃┃┣━02-进程 ┃┃┃┣━05-进程、线程的区别 ┃┃┃...

  • python多任务--进程

    一、进程 进程是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的...

  • Python多任务-进程

    进程的创建-multiprocessing multiprocessing模块就是跨平台版本的多进程模块,提供了一...

  • Python多任务_进程

    进程简单使用 Process([group [, target [, name [, args [, kwargs...

  • python多任务-进程

    程序是以二进制形式存放在硬盘之上的,当启动程序将数据(代码)加载至内存中就称之为进程。进程是一组资源(包括:代码,...

  • day24系统编程

    1python系统编程 1.1进程 1.1.1多任务的引入 单任务: 多任务: 说明: ·程序执行到os.fork...

  • 多进程和多线程编程

    多任务的实现方式: 多进程模式 多线程模式 多进程 + 多线程 模式python即支持多进程,又支持多线程,如下进...

网友评论

      本文标题:Python多任务-进程

      本文链接:https://www.haomeiwen.com/subject/iigcqhtx.html