Sadeep Weerasinghe
Sadeep Weerasinghe

Reputation: 1087

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?

Upvotes: 10

Views: 3191

Answers (2)

chiru
chiru

Reputation: 997

The default running thread is Main thread, So the next thread will be child for the main thread hence it starts form count 2.

Example:

thread count is :    1
Enumerate thread count is :  [<_MainThread(MainThread, started 140735135682560)>]
Starting Thread-1
thread count is :    2
Enumerate thread count is :  [<_MainThread(MainThread, started 140735135682560)>, <myThread(Thread-1, started 123145306509312)>]
Starting Thread-2
thread count is :    3
Enumerate thread count is :  [<_MainThread(MainThread, started 140735135682560)>, <myThread(Thread-1, started 123145306509312)>, <myThread(Thread-2, started 123145310715904)>]
Exiting Main Thread
thread count is :    3
Enumerate thread count is :  [<_MainThread(MainThread, started 140735135682560)>, <myThread(Thread-1, started 123145306509312)>, <myThread(Thread-2, started 123145310715904)>]
Thread-1: Thu Jun 28 12:44:35 2018
Thread-1: Thu Jun 28 12:44:36 2018
Thread-2: Thu Jun 28 12:44:36 2018
Thread-1: Thu Jun 28 12:44:37 2018
Thread-1: Thu Jun 28 12:44:38 2018
Thread-2: Thu Jun 28 12:44:38 2018
Thread-1: Thu Jun 28 12:44:39 2018
Exiting Thread-1
Thread-2: Thu Jun 28 12:44:40 2018
Thread-2: Thu Jun 28 12:44:42 2018
Thread-2: Thu Jun 28 12:44:44 2018
Exiting Thread-2
Enumerate thread count is :  [<_MainThread(MainThread, started 140735135682560)>]

Upvotes: -1

ShadowRanger
ShadowRanger

Reputation: 155438

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

Upvotes: 14

Related Questions