Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.