Skip to content
Advertisement

How to do a race between multiprocessors in python

I have a function that factor a number. It depends on some random condition.

So what I am trying to do it’s to run multiple processors in this function and the processor that finds the factor first returns the value and all processors terminate.

What I have so far is very wrong. The processors are not terminating and I also don’t know how to get the value that was returned by the function

JavaScript

The output is:

JavaScript

Advertisement

Answer

You can use multiprocessing.Pool and it’s methods map(), imap_unordered() etc. These will return also values from worker functions.

Example (I used time.sleep() to simulate some time-intesive computation):

JavaScript

Prints:

JavaScript

EDIT: Two different functions:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement