1

I am writing python code using parallel processing for random prime no generation. I am using Miller Rabin Algorithm to check prime nos. The parallel python code suppose to run fast as comapre to non parallel pthon code but this is not the case. Parallel processing is taking so much time. Here is my python code:

def is_prime(n, k=40):
    if n == 2 or n == 3:
        return True
    if n <= 1 or n % 2 == 0:
        return False
    # find r and s
    s = 0
    r = n - 1
    while r & 1 == 0:
        s += 1
        r //= 2
    flag=1
    jobs=[]
    event = multiprocessing.Event()
    for i in range(40):
        p = multiprocessing.Process(target=primetest,args=(s,r,n,event))
        p.start()
        jobs.append(p)
    while True:
        if event.is_set():
            flag=0
            for i in jobs:             # terminating all jobs when event is set
                Terminate each process  
                i.terminate()
            break
        else:
            flag=1
            break
            
    if flag==0:
        p.join()
        p.close()
        return False
    else:
        p.join()
        p.close()
        return True

def primetest(s,r,n,event):
    a = randrange(2, n - 1)
    v = pow(a, r, n)
    if v != 1: # this test does not apply if v is 1.
        i = 0
        while v != (n - 1):
            if i == s - 1:
                #print("value of n",n)
                event.set()
                return False
            else:
                i = i + 1
                v = (v ** 2) % n  
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
fanwer
  • 13
  • 3
  • You don't mention the size of the numbers you are testing, and whether they are randomly selected. The logic of the `while True` loop which always exits after one iteration looks wrong, and can exit with flag=1 for a number the MR test finds to be composite. Beyond that the design of this parallel implementation is very inefficient. Almost all composites will be declared composite by MR after **a single test**, rendering the remaining 39 tests superfluous. A single process will just do the one test. A better algorithm will do a single MR test and only if this passes will do the remaining. – President James K. Polk Jun 22 '21 at 13:13
  • I am testing this code for 1024 and 2048 bits. All the processes (i.e the remaining 39 processes, if alive) should be terminated whenevr there is a composite no and the test should start afresh. In case of a prime no *flag* will remain as 1. – fanwer Jun 22 '21 at 15:18
  • Added your code as is to replace my sequential miller rabin, result: 1) executed all twice, `print` lines duplicated. 2) `RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module:` – juanmf Jun 16 '22 at 04:19

0 Answers0