Baby's First Parallel Processing

Hi! I'm pretty new to python.. Let's say I have the following program:

def isEqual(inputNumber):
 if inputNumber == 69690696:
  return True
 else:
  return False


toCheck = 0
while True:
  if isEqual(toCheck):
   break
  toCheck += 1

Is there a way to change my while loop to run isEqual in parallel, until a thread returns true? I've looked at using multiprocessing.pool and apply_async, but it doesn't seem to do what I want it to do. Any help would be appreciated! ^^

Posted Dec 14, 2020, 2:30 AM UTC

27
ConflictedJew•

Create a pipe between the processes - you can send a termination signal via the pipe.

Also, your function can be shortened to:

def isEqual(inputNumber):
    return (inputNumber == 69690696)
2
socal_nerdtastic•

Yes but that would usually be done in the call, not in the loop. What's the big picture here? What do you want to do?

1
TheFinal1OP•

So, I'd like to make it so that every time the while loop calls isEqual, the function starts up on its own process, so I can have many isEqual functions running at once. I've used map() in the past, but with the large number of inputs here, that would probably be insufficient.

The bigger picture is that I have a fairly inefficient function instead of isEqual, that is called in the same exact way, and also returns a boolean. Instead of a known number like "69690696", my function ensures that its argument meets certain criteria. I figure parallelizing should increase my performance by a decent amount.

I guess my problem is that I have an unknown large amount of numbers to check, and I have to figure out a way to stop computing after any of the threads return true.

I understand my efforts should probably be spent on optimizing my actual function, but I'd also like to know how to parallelize something like this, in case I come across a similar situation in the future c:

1
socal_nerdtastic•

I see. Yes, a multiprocessing map is a good way to do this, you just need to find a way for one process to communicate to the rest to stop working. You can do that with a multiprocessing.Event object or by simply having the winning process empty the entire job queue.

1
ConflictedJew•

Hi, this is my second comment here, but here's some pseudocode on how to do this.

  1. Call isEqual in its own thread. Pass a pipe into the thread as an argument.

  2. Repeat for all needed parallelization processes.

  3. Use pipes (or queues) to coordinate between threads (IPC)

1
billsil•

Yeah...that does not work with multiprocessing well. You should assume they’ll run in any order, so your break case can hit on the first iteration.

1