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.