import threading
print threading.activeCount()
output: 2
When this code is saved into a file and run.
How could it be 2 when it's the main thread?
Does python run another thread by default in addition to the main thread when we run a foo.py file?
CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation).
Python doesn't support multi-threading because Python on the Cpython interpreter does not support true multi-core execution via multithreading. However, Python does have a threading library. The GIL does not prevent threading.
Multithreading in PythonBy default, your Python programs have a single thread, called the main thread. You can create threads by passing a function to the Thread() constructor or by inheriting the Thread class and overriding the run() method.
Generally, Python only uses one thread to execute the set of written statements. This means that in python only one thread will be executed at a time.
Psychic debugging: You're not running in a plain Python interpreter. The plain Python interpreter doesn't launch extra threads (unless you have a weird PYTHONSTARTUP
file), but other interpreters would. For example:
ipython
launches an extra thread to save command history in the background (to avoid delaying the prompt)IDLE
is designed using multiple processes communicating over a socket, and the interactive interpreter it provides you is using a daemon thread to perform the background socket communicationTry running print threading.enumerate()
; it might tell you what the background thread is doing (for example, ipython
is using a Thread
subclass named HistorySavingThread
, IDLE
s is plain Thread
, but the function it runs is named SockThread
which gives you a clue as to what it's doing).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With