CPS
CPS

Reputation: 677

Threading in Python - Threads or processes?

How are threads implemented in python? Does python create a separate process for each thread?

Consider this code.

from threading import Thread
from time import sleep


class testThread(Thread):
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        while True:
            print "Thread inner!"
            sleep(5)
threadTest = testThread()
threadTest.start()       
while True:
    print "Thread outer!"
    sleep(10)

On running this code on the shell and then doing a Ctrl+C the "Thread outer" print stops coming, however the "Thread inner" continues to get printed until i manually kill it using 'kill -9 pid' command.

Upvotes: 0

Views: 410

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Threads are not separate processes. They share the same resources as the main thread. What's going on is that Python waits for all threads to finish running before exiting.

If you want Python to exit after the main process exits, daemonize all the other threads. You can do this as follows:

...
threadTest.daemon = True
threadTest.start()
...

This will work for very basic threads. However, according to the docs (linked above):

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

Upvotes: 1

Neil
Neil

Reputation: 2438

Each Thread is a thread, not a separate process, on Linux. Use ps to see what processes are launched when your script is running, and you'll see a single python process.

The docs for the threading module note:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

...

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

Reading between the lines, the entire Python program only exits when all non-daemon threads (including the main thread) exit.

Upvotes: 1

Related Questions