0
import random
import time
import multiprocessing
import sys


start = time.time()
numbers1 = []




def NumGenerator(NumbersArray):
    while NumberCheck(NumbersArray):
        number = random.randint(0,100)
        NumbersArray.append(number)
        end = time.time()
        print(end-start)
    print('average is: ' + str(sum(NumbersArray) / len(NumbersArray)))
    print(str(NumbersArray).replace("[", "").replace("]", ""))
    sys.exit()


def NumberCheck(NumbersArray):
    # Checks if the average of the array is 50
    if NumbersArray:
        if sum(NumbersArray)/len(NumbersArray) != 50:
            return True
        else: return False
    else: return True
process1 = multiprocessing.Process(target=NumGenerator, args=(numbers1,))
process2 = multiprocessing.Process(target=NumGenerator, args=(numbers1,))
process3 = multiprocessing.Process(target=NumGenerator, args=(numbers1,))
process4 = multiprocessing.Process(target=NumGenerator, args=(numbers1,))
process1.start()
process2.start()
process3.start()
process4.start()
process1.join()
process2.join()
process3.join()
process4.join()

This is supposed to run on 4 threads and generate random numbers between 0 and 100 and add them to an array until the average of that array is 50. Currently it does the second part but on just one CPU core.

  • On a first look it appears that everything is good with the code. How are you checking that it is not running multiple threads. You may want to check task manager for this. – Daniyal Ahmed Aug 27 '17 at 18:24
  • Maybe try the threading module. Not too much different than this but certainly more guaranteed to work –  Aug 27 '17 at 18:51
  • @MohammedAbdulsattar The `multiprocessing` module doesn't run threads , it's just an API like the `threading` module, instead it runs processes, really independent processes. – GIZ Aug 27 '17 at 19:14
  • Your code works fine when I tested it. I thought initially that the division in `NumberCheck` is causing a problem, so I removed my answer. – GIZ Aug 27 '17 at 19:32
  • If you really want to share data between multiple processes it would be better to use a real [Array](https://docs.python.org/3.6/library/multiprocessing.html#multiprocessing.Array) type and not just a list, I guess. – Violet Red Aug 27 '17 at 21:40
  • Actually, no problems with multiprocessing here. You can put time.sleep(1) into your while loop in NumGenerator and see in your process manager, that several OS-processes do some work simultaneously. – Aliaksei Ramanau Aug 27 '17 at 21:46
  • It seems I was mistaken and this does run 4 processes but due to randomness getting involved one or 2 processes would end before I could run the system monitor and only 1 or 2 would remain. – Mohammed Abdulsattar Aug 28 '17 at 04:21

1 Answers1

0

Try multiprocessing.pool's ThreadPool. It follows an API similar to multiprocessing.Pool

Import with from multiprocessing.pool import ThreadPool

More info here and there

FabienP
  • 3,018
  • 1
  • 20
  • 25