1

I have a python script that starts a process using multiprocessing Process class. Inside that process I start a thread with an infinite loop, and I simulate an exception on the main thread by doing exit(1). I was expecting exit to kill the process, but it doesn't, and the main thread reports it as alive.

I have tried with both raising exception and calling exit, but none work. I have tried waiting for the process to finish by waiting for is_alive, and by calling join. But both have the same behavior.

from multiprocessing import Process
from threading import Thread
from time import sleep


def infinite_loop():
    while True:
        print("It's sleeping man")
        sleep(1)

def start_infinite_thread():
    run_thread = Thread(target=infinite_loop)
    run_thread.start()
    exit(1)

def test_multi():
    x = Process(target=start_infinite_thread)
    x.start()
    sleep(5)
    assert not x.is_alive()

I am expecting the process not to be alive, but the assert fails.

Mihai
  • 155
  • 5
  • `exit()` does not stop all the threads https://stackoverflow.com/questions/38804988/what-does-sys-exit-really-do-with-multiple-threads –  Jun 24 '19 at 07:34

1 Answers1

0

Thanks @Imperishable Night for the reply, by setting the thread as daemon the test passes. Code that works:

from multiprocessing import Process
from threading import Thread
from time import sleep


def infinite_loop():
    while True:
        print("It's sleeping man")
        sleep(1)

def start_infinite_thread():
    run_thread = Thread(target=infinite_loop)
    run_thread.daemon = True

    run_thread.start()
    exit(1)

def test_multi():
    x = Process(target=start_infinite_thread)
    x.start()
    sleep(1)
    assert not x.is_alive()
Mihai
  • 155
  • 5