为什么python线程在开始时计数为2? [英] Why is the python thread count 2 at the beginning?

查看:63
本文介绍了为什么python线程在开始时计数为2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import threading
print threading.activeCount()

输出:2

将此代码保存到文件中并运行.

When this code is saved into a file and run.

当它是主线程时怎么可能是2?

How could it be 2 when it's the main thread?

当我们运行foo.py文件时,除主线程外,python是否默认还运行另一个线程?

Does python run another thread by default in addition to the main thread when we run a foo.py file?

推荐答案

精神调试:您没有在普通的Python解释器中运行.普通的Python解释器不会启动额外的线程(除非您有一个奇怪的 PYTHONSTARTUP 文件),但是其他解释器会启动.例如:

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 启动一个额外的线程以在后台保存命令历史记录(以避免延迟提示)
  • IDLE 是使用多个进程通过套接字进行通信而设计的,它为您提供的交互式解释器正在使用守护程序线程来执行后台套接字通信
  • 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

尝试运行 print threading.enumerate();它可能会告诉您后台线程在做什么(例如, ipython 使用的是名为 HistorySavingThread IDLE 的 Thread 子类.code> s是普通的 Thread ,但是它运行的函数名为 SockThread ,这为您提供了正在执行的操作的线索).

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

这篇关于为什么python线程在开始时计数为2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆