Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread.start_new_thread vs threading.Thread.start

What is the difference between thread.start_new_thread and threading.Thread.start in python?
I have noticed that when start_new_thread is called, the new thread terminates as soon as the calling thread terminates. threading.Thread.start is the opposite: the calling thread waits for other threads to terminate.

like image 550
gmemon Avatar asked May 04 '11 11:05

gmemon


People also ask

What is difference between thread and threading?

The module "thread" treats a thread as a function, while the module "threading" is implemented in an object oriented way, i.e. every thread corresponds to an object.

What are the types of threads in Python?

There are two distinct types of thread. These are: User-level threads: These are the ones we can actively play with within our code etc. Kernel-level threads: These are very low-level threads that act on behalf of the operating system.

What are the different stages of the life cycle of a thread in Python?

A Python thread may progress through three steps of its life-cycle: a new thread, a running thread, and a terminated thread. While running, the thread may be executing code or may be blocked, waiting on something such as another thread or an external resource.

Are Python threads OS threads?

Python threads are implemented using OS threads in all implementations I know (C PythonC PythonCPython can be defined as both an interpreter and a compiler as it compiles Python code into bytecode before interpreting it. It has a foreign function interface with several languages, including C, in which one must explicitly write bindings in a language other than Python.https://en.wikipedia.org › wiki › CPythonCPython - Wikipedia, PyPyPyPyPyPy (/ˈpaɪpaɪ/) is an implementation of the Python programming language. PyPy often runs faster than the standard implementation CPython because PyPy uses a just-in-time compiler.https://en.wikipedia.org › wiki › PyPyPyPy - Wikipedia and Jython). For each Python thread, there is an underlying OS thread.


1 Answers

The thread module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. The threading module is a high-level API, built on top of thread. The Thread.start method is actually implemented using thread.start_new_thread.

The daemon attribute of Thread must be set before calling start, specifying whether the thread should be a daemon. The entire Python program exits when no alive non-daemon threads are left. By default, daemon is False, so the thread is not a daemon, and hence the process will wait for all its non-daemon thread to exit, which is the behavior you're observing.


P.S. start_new_thread really is very low-level. It's just a thin wrapper around the Python core thread launcher, which itself calls the OS thread spawning function.

like image 193
Eli Bendersky Avatar answered Nov 15 '22 21:11

Eli Bendersky