Use queue Joinablequeue, as well as knowledge of producer-consumer model

queue

Are isolated from each other between processes, to achieve the communication (IPC) between processes, multiprocess module supports two forms: the queue and the pipeline, these two methods are the use of the message passing

Create a class queue:

Queue ([maxsize]): create a shared process queue, Queue is a multi-process safe queue, you can use the Queue achieve high data transfer between multiple processes.

Introduction and parameters:

maxsize is the maximum number of entries allowed in the queue, no size limit thereof is omitted.

Methods Introduction:

put: A method for inserting data into the queue .put method has two optional parameters: blocked and timeout.

get: the method may read and remove an element from the same queue, get method has two optional parameters:. blocked and timeout.

put_nowait: use the same put, the default blocked = False

get_nowait: use the same get, the default blocked = False

empty: returns True if the queue is empty when you call this method, the results are not reliable, for example, in the process of return True, if the queue has joined the project.

full: When you call this method returns True if the queue is full, the results are not reliable, for example, in the process of return True, if the item in the queue is removed.

qsize: Returns the queue correct number of current projects, the results look unreliable, after returning result, the queue is likely to change.

Producer and consumer model

from multiprocessing import Process,JoinableQueue
import time,random
def producer(q,name):
    for i in range(10):
        print(f'生产者生产了{name}')
        time.sleep(random.randint(1, 3))
        q.put(f'{name}')

def consumer(q,name):
    while True:
        res = q.get()
        time.sleep(random.randint(1, 3))
        print(f'{name}买到了{res}')
        q.task_done()

if __name__ == '__main__':
    que = JoinableQueue()
    p = Process(target=producer, args=(que, 'apple'))
    c = Process(target=consumer, args=(que, 'con'))
    p.start()
    c.daemon = True
    c.start()
    p.join()
    que.join()

Guess you like

Origin www.cnblogs.com/cheng825/p/11529087.html