Contents

Abstract:
In Python multiprocessing, Queue and Pipe provide safe inter-process communication. Queue relies on locks and buffers to ensure data atomicity and order; Pipe implements point-to-point unidirectional/bidirectional data streams. Both have built-in serialization, simplifying the exchange process and efficiently ensuring consistency and security.

For more information about us, you can refer to the cloud document: Freak Embedded Studio Cloud Docs, or visit our wiki: https://github.com/leezisheng/Doc/wik
Original link:
Previous Recommendations:
You who study embedded systems still don't know Object Oriented? ?!
Master Python Parallel Computing in One Article: 00 Basic Concepts of Parallel Computing
For more exciting content, you can check out:
C Language 1.5 Programming Practice: Pure C Modularization × Inheritance × Polymorphism Framework
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Mastering the Debugging Principles of CM3 Microcontrollers in One Article
The "Secret Martial Arts Manual" for Computer Science Competitions
Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning
What? A motor drive module with customizable color schemes? !
What? Three new expansion boards just released for the XIAO main controller!
A Step-by-Step Guide to Publishing Third-Party Libraries for Arduino
Master the Optoelectronic Design Competition in One Read: A Must-See for Electronics Enthusiasts!
Charging over 6,000 yuan for a single conference shoot? Here are all the shooting tips and steps
Impressions of Chengdu: An Electronic Girl Created a Touch of Romance by Herself
POB: Programming Oriented to Boss — A Novel Reality-Driven Programming Paradigm
Document Acquisition:
You can download the document via the following link:
https://github.com/leezisheng/Doc
This document is a learning guide on parallel computing and Python concurrent programming, which covers the basic concepts of parallel computing, as well as the core knowledge points of Python multi-threaded programming, multi-process programming and coroutine programming:

Main Text
Processes are isolated from each other. To achieve Inter-Process Communication (IPC), the multiprocessing module supports two forms: queues and pipes.
1. Communicate using queues
Queue ([maxsize]) Returns a process-shared queue, which is both thread-safe and process-safe. Any serializable object (Python serializes objects via the pickle module) can be exchanged through it. (maxsize specifies the maximum number of items allowed in the queue; if omitted, there is no size limit.)
The main methods include:
Methods | Function |
Put() | It is used to insert data into the queue, and the put method has two optional parameters: blocked and timeout. ① If blocked is True (the default value) and timeout is a positive value, this method will block for the time specified by timeout until there is remaining space in the queue; if the timeout elapses, a Queue.Full exception will be thrown. ② If blocked is False but the Queue is full, the Queue.Full exception will be thrown immediately. |
get() | An element can be read from and removed from the queue. Similarly, the get method has two optional parameters: blocked and timeout. ① If blocked is True (the default value) and timeout is a positive value, the Queue.Empty exception will be thrown if no element is retrieved within the waiting period. ② If blocked is False, there are two possible cases: if a value is available in the Queue, this value will be returned immediately; otherwise, if the queue is empty, the Queue.Empty exception will be thrown immediately. |
get_nowait() | Same as q.get(False) |
put_nowait() | Same as q.put(False) |
empty() | When this method is called, it returns True if q is empty, but this result is unreliable — for example, new items may be added to the queue while the True result is being returned. |
full() | When this method is called, it returns True if the queue q is full; this result is not reliable, for example, an item in the queue may be removed while the True result is being returned. |
qsize() | Returns the correct number of items currently in the queue, but the result is also unreliable for the same reasons as q.empty () and q.full (). |
cancel_join_thread() | will not automatically connect to the background thread when the process exits, which can prevent the join_thread () method from blocking |
close() | Closes the queue to prevent more data from being added to it. When this method is invoked, the background thread will continue to write the data that has already been enqueued but not yet written, but will close immediately once this method completes. This method will be called if q is garbage collected. Closing the queue will not generate any type of end-of-data signal or exception among queue users. For example, if a user is blocked on a get () operation, closing the queue in the producer will not cause the get () method to return an error. |
join_thread() | A background thread for the connection queue. This method is used to wait for all queue items to be consumed after the q.close () method is called. By default, this method is called by all processes that are not the original creator of q. Calling the q.cancel_join_thread method can disable this behavior |
In the following example, the Producer class produces items and places them into a queue, after which the Consumer class removes those items from the queue.
import multiprocessing
import random
import time
class Producer(multiprocessing.Process):
def __init__(self, queue):
multiprocessing.Process.__init__(self)
self.queue = queue
def run(self):
for i in range(10):
item = random.randint(0, 256)
self.queue.put(item)
print("Process Producer : item %d appended to queue %s" % (item, self.name))
time.sleep(1)
print("The size of queue is %s" % self.queue.qsize())
class Consumer(multiprocessing.Process):
def __init__(self, queue):
multiprocessing.Process.__init__(self)
self.queue = queue
def run(self):
while True:
if self.queue.empty():
print("the queue is empty")
break
else:
time.sleep(2)
item = self.queue.get()
print('Process Consumer : item %d popped from by %s \n' % (item, self.name))
time.sleep(1)
if __name__ == '__main__':
queue = multiprocessing.Queue()
process_producer = Producer(queue)
process_consumer = Consumer(queue)
process_producer.start()
process_consumer.start()
process_producer.join()
process_consumer.join()
The drawback of this code is that the main process will terminate prematurely in scenarios where production is slow but consumption is fast. One solution is to have the producer send an additional termination signal to the queue after it finishes production, so that the consumer can break out of the infinite loop upon receiving this termination signal.
However, a new problem arises: when there are multiple producers and multiple consumers, an end signal needs to be sent as many times as there are consumers, which is extremely cumbersome. In fact, our core idea is simply to send an end signal, and there is another type of queue that provides such a mechanism.
The queue also has a JoinableQueue subclass, which has the following two additional methods:
task_done (): Called by a consumer to indicate that a previously enqueued task has been completed; for example, after theget ()method retrieves anitemfrom the queue, calling this method signals that the item returned byq.get ()has been processed. If this method is called more times than the number of items removed from the queue, aValueErrorexception will be raised.join (): The producer calls this method to block until all items in the queue have been processed. The blocking will persist until every item in the queue has called thetask_done ()method.
The sample code is as follows:
from multiprocessing import Process,JoinableQueue
import time,random,os
def consumer(q):
while True:
res=q.get()
time.sleep(random.randint(1,3))
print('\033[45m%s 吃 %s\033[0m' %(os.getpid(),res))
# Send one signal to q.join(), showing that one item has been taken away
q.task_done()
def producer(name,q):
for i in range(10):
time.sleep(random.randint(1,3))
res='%s%s' %(name,i)
q.put(res)
print('\033[44m%s 生产了 %s\033[0m' %(os.getpid(),res))
q.join()
if __name__ == '__main__':
q=JoinableQueue()
#Producers: i.e. the chefs
p1=Process(target=producer,args=('包子',q))
p2=Process(target=producer,args=('骨头',q))
p3=Process(target=producer,args=('泔水',q))
#Consumers: i.e. the foodies
c1=Process(target=consumer,args=(q,))
c2=Process(target=consumer,args=(q,))
c1.daemon=True
c2.daemon=True
#Start
p_l=[p1,p2,p3,c1,c2]
for p in p_l:
p.start()
p1.join()
p2.join()
p3.join()
print('主') 
2. Communicate Using Pipes
A pipe is one of the most fundamental Inter-Process Communication mechanisms. A data stream that connects one process to another is referred to as a "pipe", which is typically used to channel the output of one process via the pipe to the input of another. Essentially, a pipe is a block of cache in the kernel: the kernel maintains a buffer associated with the pipe file, and all operations performed on the pipe file are converted by the kernel into operations on this buffer memory.
The characteristics of pipe communication include:
- Pipes transmit data in the form of streams for information transmission and have no message boundaries, so they are generally used for communication between two processes;
- The read-write efficiency of pipes is higher than that of queues;
- A pipe is a type of file that can invoke
read,write,closeand other file operation interfaces to perform operations. On the other hand, a pipe is not an ordinary file; it belongs to a unique file system:pipefs. - Inter-process
Pipeis established based on theforkmechanism:- When the main process creates a
Pipe, bothConnectionsof the Pipe are connected to the main process. - After the main process creates a child process,
Connectionsare also copied once. At this point, there are 4Connections. - After that, close one
Out Connectionof the main process, and close oneIn Connectionof a child process. Then a pipe with input at the main process and output at the child process is established.
- When the main process creates a



In the following sample program, we create a pipe in the main process, and the main process has the right to use both the conn1 and conn2 instances'. send () and. recv () methods.Next, we create a child process in the main process, and at the same time conn1 and conn2 are passed to the child process as parameters. At this point, both main and sub_process have access to conn1 and conn2, which means that both main and sub_process have the right to use the conn1 and conn2 instances, including the permission to call their. send () and. recv () methods.
The control relationship between the two processes and the two ports is shown in the following figure:

from multiprocessing import Process, Pipe
import time
# Create two pipe endpoint objects
# Pipe has the default parameter duplex=True, meaning each endpoint is full-duplex,
# i.e. both the .send() and .recv() methods are available
conn1, conn2 = Pipe(duplex=True)
def worker(x, pipe):
conn1, conn2 = pipe
# Verify that sub_process can control conn2's receiving
msg = conn2.recv()
time.sleep(1)
if msg == "conn1s":
print("conn2 receives msg in sub_p!")
# Verify that sub_process can control conn2's sending
conn2.send("conn2s")
# Verify that sub_process can control conn1's receiving
msg = conn1.recv()
if msg == "conn2s":
print("conn1 receives msg in sub_p!")
# Verify that sub_process can control conn1's sending
conn1.send("conn1s")
if __name__ == '__main__':
conn1, conn2 = Pipe(True)
sub_process = Process(target=worker, args=(100, (conn1, conn2)))
sub_process.start()
# Verify that main can control conn1's sending
conn1.send("conn1s")
msg = conn1.recv()
time.sleep(1)
if msg == "conn2s":
# Verify that main can control conn1's receiving
print("conn1 receives msg in main_p!")
# Verify that main can control conn2's sending
conn2.send("conn2s")
msg = conn2.recv()
time.sleep(2)
if msg == "conn1s":
# Verify that main can control conn2's receiving
print("conn2 receives msg in main_p!")Finally, note that when using the. close () method of a pipe port to revoke the current process's control permission over a port, you need to call conn in all processes that can control it conn.close ().
Other usage methods of the connection object include:
