Inter-process Communication | Teach You to Get Started With Python One Hundred and Seven

Use the producer-consumer case to explain the problem of interprocess communication.

Inter-process communication.interprocess communication

Interprocess communication - Queue
from multiprocessing import Queue
q =Queue(3) #Initialize a Queue object that can receive up to three put messages
q.put ( "message 1" )
q.put ( "message 2" )
print ( q.full ()) #False
q.put ( "message 3" )
print ( q.full ()) #True

#Because the message queue is full, the following try will throw an exception, the first try will wait 2 seconds before throwing an exception, and the second try will throw an exception immediately
try:
q.put ( "message 4" , True , 2)
except:
print ( "Message queue full, number of existing messages: %s" % q.qsize ())

try:
q.put_nowait ( "message 4" )
except:
print ( "Message queue full, number of existing messages: %s" % q.qsize ())

#Recommended method, first determine whether the message queue is full, and then write
if not q.full ():
q.put_nowait ( "message 4" )

#When reading a message, first determine whether the message queue is empty, and then read
if not q.empty ():
for i in range( q.qsize ()):
print ( q.get_nowait ( ) )
Description:
When initializing the Queue() object (for example: q=Queue()), if the maximum number of messages that can be received is not specified in the parentheses, or the number is negative, it means that there is no upper limit on the number of acceptable messages (until the memory end);
•Queue.qsize (): Returns the number of messages contained in the current queue;
•Queue.empty (): If the queue is empty, return True, otherwise False;
•Queue.full (): If the queue is full, return True, otherwise False;
•Queue.get ([block[, timeout]]): Get a message in the queue, and then remove it from the queue, the default value of block is True;
1 ) If the default value of block is used, and timeout (unit seconds ) is not set ), if the message queue is empty, the program will be blocked (stop in reading state) until the message is read from the message queue, if timeout is set, it will wait for timeout seconds, if no message has been read yet , the " Queue.Empty " exception is thrown ;
2) If the block value is False, if the message queue is empty, the " Queue.Empty " exception will be thrown immediately;
•Queue.get_nowait (): equivalent to Queue.get (False);
•Queue.put (item,[block[, timeout]]): Write the item message to the queue, the default value of block is True;
1) If the default value of block is used and the timeout (in seconds ) is not set, if the message queue has no space to write, the program will be blocked (stop in the writing state) until space is vacated from the message queue. If timeout is set, it will wait for timeout seconds, if there is no space, it will throw " Queue.Full " exception;
2) If the block value is False, if there is no space to write in the message queue, the " Queue.Full " exception will be thrown immediately;
•Queue.put_nowait (item): equivalent to Queue.put (item, False);
Example:
import os , multiprocessing, time


def producer(x):
for i in range(10):
time.sleep(0.5)
print('生产了+++++++pid{} {}'.format(os.getpid(), i))
x.put('pid{} {}'.format(os.getpid(), i))


def consumer(x):
for i in range(10):
time.sleep(0.3)
print('消费了-------{}'.format(x.get()))


if __name__ == '__main__':
q = multiprocessing.Queue()

p1 = multiprocessing.Process(target=producer, args=(q,))
p2 = multiprocessing.Process(target=producer, args=(q,))
p3 = multiprocessing.Process(target=producer, args=(q,))
p1.start()
p2.start()
p3.start()

c2 = multiprocessing.Process(target=consumer, args=(q,))
c2.start()


Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00