Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What if we call thread.start() and leave it without join or close?

When I create a new thread from threading like this:

def hello():
    print ('hello')
t1 = threading.Thread(target=hello)
t1.start()

If I creating more and more threads like that, would I be out of memory or threads to use? Is it ok to leave it like that after call start method?

like image 463
Anh Vũ Nguyễn Avatar asked Apr 19 '18 02:04

Anh Vũ Nguyễn


People also ask

What happens if you don't join a thread in Python?

A Python thread is just a regular OS thread. If you don't join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception.

What happens when we call thread start ()?

start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

Do Python threads need to be joined?

Need to Join a ThreadEvery Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system. Sometimes we may need to create additional threads in our program in order to execute code concurrently.

Do you have to close a thread Python?

We can close a Python thread immediately by raising an Error or Exception that is not caught. Because it is not caught, it will unravel the call graph from our custom functions, back up to the run() function, then terminate the new thread.


1 Answers

Yes, if you create a lot of long-running threads, it is theoretically possible to hit the functional OS max for the python process (about 2-3k threads on 32-bit machines, or around 30k for 64-bit machines).

However, it doesn't really matter if you join() the threads or not. The threads will automatically exit when the target function returns.

like image 70
Brendan Abel Avatar answered Sep 30 '22 07:09

Brendan Abel