3
votes

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:

  • As many instances of multiprocessing code, this code runs in the terminal rather than in IDEs.

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.

1
A value cannot be a string, and you're getting an error that's not immediately being displayed due to the way multiprocessing handles stdout. you can't assign a string to a Value which can only be a single character. Strings need to be an array of characters. Better yet, check the user input in the main process, and then use a numeric value set to either 0 or 1 to signal the child. - Aaron
You are right. thanks you! I changed the corresponding stings to characters ('STOP' to 'S' and ' ' to 'a') and all problems were solved - Charalamm
It's a little bit of a trap with python that there's no "char" data type like other languages. In python a "char" is actually a "string" of length 1. Other languages have a clear delineation between "char" and "string" (array of type char) - Aaron
@Charalamm any feedback? - Artiom Kozyrev
@Artiom I haven't had the time yet to test it. Thanks for your answer, it seems helpful and correct. I will give feedback as soon as possible. - Charalamm

1 Answers

2
votes

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.