python learning Notes eleven jobs

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/QWERTY1994/article/details/81903915
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2018/8/20 17:01
# @Author   :



# 多进程
from multiprocessing import Process
import os

# 子进程要执行的代码
def run_proc(name):
    print("Run child process %s ((%s)"%(name,os.getppid()))

if __name__ == '__main__':
    print("Parent process %s."%os.getpid())
    p = Process(target=run_proc,args=('test',))
    print('Child process will start.')
    p.start()
    p.join() #等待子进程结束后再继续往下运行,通常用于进程间的同步
    print("Child process end.")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2018/8/20 17:06
# @Author   :

# 要启动大量的子进程,可以用进程池的方式批量创建子进程:
from multiprocessing import Pool
import os,time,random
def long_time_task(name):
    print('Run task %s (%s)..'%(name,os.getpid()))
    start =time.time()
    time.sleep(random.random()*3)
    end = time.time()
    print('Task %s runs %0.2f seconds.'%(name,(end-start)))

if __name__ == '__main__':
    print('Parent process %s.'%os.getpid())
    p =Pool(4) # 参数 4表示可以同时跑4个线程 可以不赋值 默认cpu核数
    for i in range(5):
        p.apply_async(long_time_task,args=(i,))
    print('Waiting for all subProcess done...')
    p.close()
    p.join() #对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了
    print('All subProcess done.')

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2018/8/20 17:14
# @Author   : 

# 前面讲的都是子进程都是自己的代码 ,很多时候我们都是不同代码的进程协同工作
import subprocess

print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2018/8/20 17:21
# @Author   : 

# 进程之间的通信 提供了Queue、Pipes等多种方式来交换数据。
from multiprocessing import  Process,Queue
import os,time,random

# 写进程执行的代码
def write(q):
    print('Process to write:%s'%os.getpid())
    for value in range(ord('A'),ord('D')):
        print('Put %s to queue...' %chr(value))
        q.put(chr(value))
        time.sleep(random.random())
# 读数据进程执行的代码
def read(q):
    print('Process to read: %s' %os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.'%value)

if __name__ =='__main__':
    # 父进程创建Queue 并传输给各个子进程
    q = Queue()
    pw = Process(target=write,args=(q,))
    pr = Process(target=read,args=(q,))
    # 启动进程
    pw.start()
    pr.start()
    #等待pw结束
    pw.join()
    # pr是死循环 无法结束 强制结束
    pr.terminate()

 

Guess you like

Origin blog.csdn.net/QWERTY1994/article/details/81903915