There is no straightforward way to control the order in which multiple print outputs are displayed after executing multiprocessing. This is because the order in which the processes are executed is not deterministic and depends on various factors such as the operating system, system resources, and the number of processors.
However, one possible workaround is to use a synchronization primitive such as a Queue or a Lock to enforce a specific order in which the print statements are executed. Here is an example using a queue:
import multiprocessing as mp
def worker(q, msg):
q.put(msg)
if __name__ == '__main__':
q = mp.Queue()
jobs = []
jobs.append(mp.Process(target=worker, args=(q, "Message 1")))
jobs.append(mp.Process(target=worker, args=(q, "Message 2")))
jobs.append(mp.Process(target=worker, args=(q, "Message 3")))
for j in jobs:
j.start()
for j in jobs:
j.join()
while not q.empty():
print(q.get())
In this example, we spawn three processes that put messages into a shared queue. We then wait for all the processes to finish using the join()
method and print the messages in the order they were added to the queue.
Note that this approach may not be practical if the number of messages is very large, as it may lead to memory issues. In such cases, you may consider storing the messages in a file or a database and reading them later in a deterministic order.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-07-16 11:00:00 +0000
Seen: 8 times
Last updated: Sep 11 '21
Can specific order be programmed to add rows to DataGridView?
Is the Nextflow channel processing only the first item in the channel?
In order to match the page with Tampermonkey, how can I disregard all the forward slashes?
What is the way to identify boolean queries that are not valid, and do not have parentheses?
How can we group pandas data by a column and sort it in a descending order?
If the values above and below are identical, how can you complete the missing cells in sequence?
How can DICOM Tags be transmitted to a Modality in order to generate a DICOM file?