Charalamm
Charalamm

Reputation: 1937

Terminate infinite loop

I am trying to create a program that runs an infinite loop in parallel and exits the loops when it is told too. Specifically, the infinite loop is in the square function and the exiting signal is given when shv='STOP'. When all processes read that signal will have to exit the infinite loop and return.

The problem is that the Processes do not close even after giving the STOP signal.

Some notes:

The code:

import multiprocessing as mp
import time
import ctypes


def square(x, shv):

    while shv.value != 'STOP':
        time.sleep(3)
        print(shv.value)
    else:
        print('stopped')

    return


if __name__ == '__main__':
    stopphrase = 'STOP'
    proecess_num = 2

    shv = mp.Value(ctypes.c_wchar_p, '')

    processes = [mp.Process(target=square, args=(i, shv)) for i in range(proecess_num)]
    for p in processes:
        p.start()
    print('Mapped & Started')
    print(processes)

    while shv.value != stopphrase:
        inp = input('Type STOP and press Enter to terminate: ')
        if inp == stopphrase:
            shv.value = stopphrase
            time.sleep(2)
    p.terminate()
    print(processes)

For some reason this code gives the following in both cases of print(processes) even though I set the shv.value = stopphrase:

[<Process name='Process-1' pid=9664 parent=6084 started>, <Process name='Process -2' pid=10052 parent=6084 started>]

Please let me know for further improvements or details of the question.

Upvotes: 3

Views: 765

Answers (1)

quamrana
quamrana

Reputation: 39354

I think you meant to have a loop calling ‘join()’ on each process.

for p in processes:
    p.join()

instead of calling terminate on just one of them.

Upvotes: 2

Related Questions