Aryan Robin
Aryan Robin

Reputation: 1

Why the process is not terminated?

I am new to multithreading. While reading 'Programming Python' by Mark Lutz I stuck at this line

note that because of its simple-minded infinite loops, at least one of its threads may not die on a Ctrl-C on Windows you may need to use Task Manager to kill the python.exe process running this script or close this window to exit

But according to my little knowledge about threading all thread terminate when main thread exits. So why not in this code?

# anonymous pipes and threads, not process; this version works on Windows


import os
import time
import threading


def child(pipe_out):
    try:
        zzz = 0
        while True:
            time.sleep(zzz)
            msg = ('Spam %03d\n' % zzz).encode()
            os.write(pipe_out, msg)
            zzz = (zzz + 1) % 5
    except KeyboardInterrupt:
            print("Child exiting")


def parent(pipe_in):
    try:
        while True:
            line = os.read(pipe_in, 32)
            print('Parent %d got [%s] at %s' % (os.getpid(), line, time.time()))
    except KeyboardInterrupt:
        print('Parent Exiting')


pipe_in, pipe_out = os.pipe()
threading.Thread(target=child, args=(pipe_out, )).start()
parent(pipe_in)
print("main thread exiting")

Upvotes: 0

Views: 368

Answers (1)

kingkupps
kingkupps

Reputation: 3534

A Python process will end when there are no more running non-daemon threads. If you pass the daemon=True argument to threading.Thread you will notice different behavior in your program.

I suggest reading the docs for the threading module to learn more about what I'm talking about.

Upvotes: 1

Related Questions