Python中的 进程问题详解。守护进程,互斥锁,队列,IPC等介绍

口说不如身逢,耳闻不如目见。

嘴上说不如亲身做,耳听为虚,一定要亲眼看到。

1 进程调度

# 1 先来先服务
# 2 短作业优先
# 3 时间片轮转
# 4 多级反馈队列
# 易语言

2 僵尸进程与孤儿进程

#1 僵尸进程:进程结束了,资源还没来得及回收
#2 孤儿进程:主进程挂了,子进程还没结束,它就会被专门的进程接管

3 进程对象及其他方法

# 1 windows:tasklist |findstr 进程id号
# 2 mac,Linux:ps aux | grep 进程id号
# 3 进程对象:t=Process(target=task, )或者是在进程内部:current_process()
# 4 t.pid或者current_process().pid   获取进程id号
# 5 os.getpid() 同上,获取进程id号
# 6 os.getppid() 获取父进程id号,子进程中获取父进程id,等于父进程的id号
# 7 t.is_alive()或者current_process().is_alive()  查看进程是否存活
# 8 t.terminate() 关闭进程,在主进程关闭

4 守护进程

from multiprocessing import Process,current_process
import time
import os

def task():
    print(os.getpid())
    print('子进程')
    time.sleep(200)
    print('子进程结束')


if __name__ == '__main__':
    t = Process(target=task, )
    # 守护进程:主进程一旦结束,子进程也结束
    # t.daemon=True  # 一定要加在启动之前
    t.start()


    time.sleep(1)
    print('主进程结束')

5 互斥锁

# 同时只有一个人能拿到,必须释放,其他人才能再次获取到

from multiprocessing import Process, Lock
import json
import time
import random


def search():
    # 查票的函数
    # 打开文件,读出ticket_count
    with open('ticket', 'r', encoding='utf-8') as f:
        dic = json.load(f)
        print('余票还有:', dic.get('ticket_count'))


def buy():
    with open('ticket', 'r', encoding='utf-8') as f:
        dic = json.load(f)

    time.sleep(random.randint(1, 3))  # 模拟一下网络延迟
    if dic.get('ticket_count') > 0:
        # 能够买票
        dic['ticket_count'] -= 1
        # 保存到文件中去
        with open('ticket', 'w', encoding='utf-8') as f:
            json.dump(dic, f)
            print('买票成功')
    else:
        # 买票失败
        print('买票失败')


# 写一个函数,先查票,再买票

def task(mutex):
    search()
    # 买票过程要加锁
    # 买前加锁
    # mutex.acquire()
    # buy()  # 10个进程变成了串行执行
    # # 买后释放锁
    # mutex.release()
    with mutex:
        buy()


if __name__ == '__main__':
    # 锁的创建,在哪?主进程创建锁
    mutex = Lock()  # 创建一把锁
    # 模拟十个人买票(开10个进程)
    for i in range(10):
        t = Process(target=task, args=(mutex,))
        t.start()


6 队列介绍


from multiprocessing import Queue

# 实例化得到要给对象

q=Queue(5)  # 默认很大,可以放很多,写了个5,只能放5个

# 往管道中放值
q.put(1)
q.put('lqz')
q.put(18)
q.put(19)
# q.put(20)
# q.put(21)
# q.put_nowait(100)

# 从管道中取值
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get(timeout=100))  # 等0.1s还没有值,就结束
# print(q.get_nowait())        # 不等了,有就是有,没有就没有

print(q.empty())  # 看一下队列是不是空的
print(q.full())   # 看一下队列是不是满的


# 总结:
'''
q=Queue(队列大小)
# 放值
q.put(asdf)
q.put_nowait(asdf)  # 队列满了,放不进去就不放了,报错

# 取值
q.get()  # 从队列头部取出一个值
q.get_nowait() # 从队列头部取值,没有就抛错


# 队列是否为空,是否满
print(q.empty())  # 看一下队列是不是空的
print(q.full())   # 看一下队列是不是满的
'''


3.7 IPC机制(进程间通信)

# Inter-Process Communication,进程间通信
from multiprocessing import Process, current_process, Queue
import time
import os


def task1(q):
    print('我是task1进程,我的id号是:%s'%os.getpid())
    q.put('lqz is handsome')


def task2(q):

    # res=q.get()
    # print('我是task2进程,我的id号是:%s'%os.getpid(),res)
    print('我是task2进程,我的id号是:%s'%os.getpid())


if __name__ == '__main__':
    q = Queue(5)

    t1 = Process(target=task1, args=(q,))
    t1.start()
    t2 = Process(target=task2, args=(q,))
    t2.start()

    print(q.get())



努力学习!
原文地址:https://www.cnblogs.com/Orange-YXH/p/13648094.html