【问题标题】:Why doesn't python reclaim dangling threads?为什么 python 不回收悬空线程?
【发布时间】:2019-02-23 14:20:42
【问题描述】:

这是 Python 的 sn-p 代码。正如标准输出所示,活动线程不断增加,直到 os 抱怨您有太多线程。为什么python在所有任务完成后不回收thread_pool中的线程?

from multiprocessing.dummy import Pool as ThreadPool
import threading

count = 0

def fun(i):
    pass

while True:
    count += 1
    data = list(range(1, 100))
    thread_pool = ThreadPool(30)
    thread_pool.map(fun, enumerate(data))
    print(count, 'end', threading.active_count())

【问题讨论】:

  • 什么stdout?你忘了包括什么吗?
  • print 默认输出到sys.stdout
  • 你说,“正如标准输出显示的那样”,但你没有显示任何东西。
  • 线程池的全部意义在于重用。为什么你的程序只能创建和重用一个线程池,而它却继续创建新的线程池?
  • 很少有任何程序有正当理由创建多个线程池。您是否尝试过将thread_pool=ThreadPool(30) 移动到while True: 之前的行会发生什么?

标签: python multithreading multiprocessing threadpool


【解决方案1】:

如果您希望事情正确终止,请使用上下文管理器

with ThreadPool(30) as pool:
    pool.map(fun, enumerate(data))

【讨论】:

  • 是的,它有一个上下文管理器。现在只运行代码,如果您使用上下文管理器,线程不会运行。
  • 哦,new in 3.3
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
相关资源
最近更新 更多