Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the python thread count 2 at the beginning?

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?

like image 921
SadeepDarshana Avatar asked Nov 07 '16 18:11

SadeepDarshana


People also ask

How many threads can Python start?

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).

Is Python actually multithreaded?

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.

Is Python multithreaded by default?

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.

How many threads should I run Python?

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.


1 Answers

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 communication

Try running print threading.enumerate(); it might tell you what the background thread is doing (for example, ipython is using a Thread subclass named HistorySavingThread, IDLEs is plain Thread, but the function it runs is named SockThread which gives you a clue as to what it's doing).

like image 118
ShadowRanger Avatar answered Sep 21 '22 02:09

ShadowRanger