Ask Your Question
2

How to control the order in which multiple print outputs are displayed after executing multiprocessing?

asked 2022-07-16 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-09-11 11:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-07-16 11:00:00 +0000

Seen: 8 times

Last updated: Sep 11 '21