zoukankan      html  css  js  c++  java
  • Python在程序中进行多任务操作-进程

    进程的创建-multiprocessing

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

    # -*- coding:utf-8 -*-from multiprocessing import Processimport timedef 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 Processimport osimport timedef 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 Processimport osfrom time import sleepdef 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 Processimport osimport timenums = [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, Queueimport 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:            breakif __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知识和【免费】工具

     

    耐得住寂寞,才能登得顶
    Gitee码云:https://gitee.com/lyc96/projects
  • 相关阅读:
    【NOIP2007】守望者的逃离
    20200321(ABC)题解 by 马鸿儒 孙晨曦
    20200320(ABC)题解 by 王一帆
    20200319(ABC)题解 by 王一帆 梁延杰 丁智辰
    20200314(ABC)题解 by 董国梁 蒋丽君 章思航
    20200309(ABC)题解 by 梁延杰
    20200307(DEF)题解 by 孙晨曦
    20200306(ABC)题解 by 孙晨曦
    20200305(DEF)题解 by 孙晨曦
    20200303(ABC)题解 by 王锐,董国梁
  • 原文地址:https://www.cnblogs.com/chenlove/p/14038627.html
Copyright © 2011-2022 走看看