2 concurrent multi-process programming

Get pid

The current process point of view

os.getpid () Gets the current process pid

os.getppid () # get the parent process pid of the current process

The child objects .pid # obtain a child process pid the current process

Zombie process and orphaned

Zombie process (harmful): The exit (after) still have pid, did not immediately disappear, the parent process to wait for treatment

If you have a large number of zombie process, not only the process ID will cause the system can not produce a new process, this process should avoid harm

Orphaned (harmless): The parent process exits one or more sub-process is still run by the init process to complete their processing status

init process handles all his rehabilitation work.

Daemon

  • Broke into the master daemon process
    • Daemon will terminate after the end of the main process code execution.
    • Within daemon can no longer turn a child process, otherwise an exception is thrown.
  • Between processes are independent of each other, the end of the main process code to run, stop the daemon

  • def task(x):
        print(f'{x} start')
        time.sleep(2)
        print(f'{x} end')
    
    if __name__ == '__main__':
        p=Process(target=task,args=('sb',))
        p.daemon = True ##一定要在p.start()前设置,设置p为守护进程,禁止p创建子进程,并且父进程代码执行结束,p即终止运行
        p.start()
    
        print('主')
    
    

Object .join ()

A request to the operating system, and then inform the operating system do not need the id p is occupied, can be recovered

But will remain a pid, zombie

from multiprocessing import Process
import time,os

def task():
    print('%s is running' %os.getpid())
    time.sleep(3)
    
if __name__ == '__main__':
    p=Process(target=task)
    p.start()
    p.join() # 等待进程p结束后,join函数内部会发送系统调用wait,去告诉操作系统回收掉进程p的id号

    print(p.pid) #此时能看到子进程p的id号
    print('主')

is_alive()

Determine whether the process is already running End

terminate

Direct terminate processes running

Analog grab votes applet

Multiple processes to share a file

When the database file, analog to grab votes

from  multiprocessing import Process
import json,time,os

def search():
    time.sleep(1) # 模拟网络io
    with open('db.txt',mode='rt',encoding='utf-8') as f:
        res = json.load(f)
        print(f'还剩{res["count"]}')

def get():
    with open('db.txt',mode='rt',encoding='utf-8') as f:
        res = json.load(f)
        # print(f'还剩{res["count"]}')
    # time.sleep(1) # 模拟网络io
    if res['count'] > 0:
        res['count'] -= 1
        with open('db.txt',mode='wt',encoding='utf-8') as f:
            json.dump(res,f)
            print(f'进程{os.getpid()} 抢票成功')
        time.sleep(1.5) # 模 拟网络io

    else:
        print('票已经售空啦!!!!!!!!!!!')

def task():
    search()
    get()

if __name__ == '__main__':
    for i in range(15):
        p = Process(target=task)
        p.start()
        # p.join()


# 为了保证数据的安全,要牺牲掉效率.

Guess you like

Origin www.cnblogs.com/jhpy/p/11514944.html