程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Process summary of Python interview questions

編輯:Python

One 、 process :

process : An instance of program running on the operating system , It's called the process . The process needs the corresponding system resources : Memory 、 Time slice 、pid. Create a process : Import first multiprocessing Medium Process: Create a Process object ; establish Process Object time , Parameters can be passed ;

example 1: Don't use p.join()

import os
from multiprocessing import Process
import time
def pro_func(name):
for i in range(5):
print(f' Subprocesses {
name+str(i)} Start execution ')
time.sleep(2)
print(f' Subprocesses {
name+str(i)} End to perform ')
if __name__ == '__main__':
p=Process(target=pro_func,args=('kobe',))
p.start()
print(' The execution of the main process is over ')

Execution results :

The execution of the main process is over
Subprocesses kobe0 Start execution
Subprocesses kobe0 End to perform
Subprocesses kobe1 Start execution
Subprocesses kobe1 End to perform
Subprocesses kobe2 Start execution
Subprocesses kobe2 End to perform
Subprocesses kobe3 Start execution
Subprocesses kobe3 End to perform
Subprocesses kobe4 Start execution
Subprocesses kobe4 End to perform

example 2: Use p.join(): Blocking function , Wait for all child processes to complete execution , The main process ends execution

import os
from multiprocessing import Process
import time
def pro_func(name):
for i in range(5):
print(f' Subprocesses {
name+str(i)} Start execution ')
time.sleep(2)
print(f' Subprocesses {
name+str(i)} End to perform ')
if __name__ == '__main__':
p=Process(target=pro_func,args=('kobe',))
p.start()
p.join()
print(' The execution of the main process is over ')

Execution results :

Subprocesses kobe0 Start execution
Subprocesses kobe0 End to perform
Subprocesses kobe1 Start execution
Subprocesses kobe1 End to perform
Subprocesses kobe2 Start execution
Subprocesses kobe2 End to perform
Subprocesses kobe3 Start execution
Subprocesses kobe3 End to perform
Subprocesses kobe4 Start execution
Subprocesses kobe4 End to perform
The execution of the main process is over

example 3:p.terminate(): Kill child process

import os
from multiprocessing import Process
import time
def pro_func(name):
for i in range(5):
print(f' Subprocesses {
name+str(i)} Start execution ')
time.sleep(2)
print(f' Subprocesses {
name+str(i)} End to perform ')
if __name__ == '__main__':
p=Process(target=pro_func,args=('kobe',))
p.start()
p.terminate()
p.join()
print(' The execution of the main process is over ')

Execution results :

The execution of the main process is over

Two 、 Communication between processes -Queue

Initializing Queue() Object time ( for example q=Queue(), If the maximum number of acceptable messages is not specified in parentheses , When the obtained quantity is negative , That means there is no upper limit on the number of acceptable messages until the end of memory )

Queue.qsize(): Returns the number of messages contained in the current queue
Queue.empty(): If the queue is empty , return True, conversely False
Queue.full(): If the queue is full , return True, conversely False
Queue.get([block[,timeout]]): Gets a message in the queue , Then remove it from the queue ,block Default
The value is True.

If block Use the default value , And it's not set timeout( Unit second ), If message queue is empty , At this point the program will be blocked ( Stop in reading state ), Until the message queue reads the message , If set timeout, Will be waiting for timeout second , If no message has been read , Throw out “Queue.Empty" abnormal :

Queue.put(item,[block[,timeout]]): take item Message writing queue ,block The default value is True; If block Use the default value , And it's not set timeout( Unit second ), If the message queue has no space to write , At this point the program will be blocked ( Stop in write state ), Until space is made available from the message queue , If set timeout, Will be waiting for timeout second , If there's no room , Throw out ”Queue.Full" abnormal If block The value is False, If the message queue has no space to write , It will be thrown immediately "Queue.Full" abnormal ; Queue.put_nowait(item): Quite a Queue.put(item,False)

example 4:

from multiprocessing import Process,Queue
import os,time,random
def write(q):
for i in range(6):
print(f' Production of products {
i}')
q.put(f' Production of products {
i}, Add to queue ')
time.sleep(2)
def read(q):
while True:
if not q.empty():
value=q.get(True)
print(f' Got the product {
value}')
time.sleep(2)
else:
break
if __name__ == '__main__':
q=Queue()
pw=Process(target=write,args=(q,))
pr=Process(target=read,args=(q,))
pw.start()
pr.start()
pw.join()
pr.join()
print(' All data is written and read ')

Execution results :

Production of products 0
Get the product and produce the product 0, Add to queue
Production of products 1
Get the product and produce the product 1, Add to queue
Production of products 2
Get the product and produce the product 2, Add to queue
Production of products 3
Get the product and produce the product 3, Add to queue
Production of products 4
Get the product and produce the product 4, Add to queue
Production of products 5
Get the product and produce the product 5, Add to queue
All data is written and read

3、 ... and 、 Use... In the process pool Queue

If you want to use Pool Create a process , You need to use multiprocessing.Manager() Medium Queue(), instead of multiprocessing.Queue(), Otherwise, you will get the following error message :
RuntimeError: Queue objects should only be shared between processs through inheritance

example 5

from multiprocessing import Manager,Pool
import os,time,random
def write(q):
for i in range(6):
q.put(f' product {
i}')
print(f' product {
i} Production of complete ')
time.sleep(1)
def read(q):
while True:
if not q.empty():
value=q.get(True)
print(f' Got it {
value}')
time.sleep(2)
if __name__ == '__main__':
print(f' The main process starts executing , The process number is {
os.getpid()}')
q=Manager().Queue()
po=Pool(3)
po.apply_async(func=write,args=(q,))
po.apply_async(func=read,args=(q,))
po.close()
po.join()
print(f' The main process ends execution , The process number is {
os.getpid()}')

Execution results


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved