【问题标题】:python threading: max number of threads to runpython threading:要运行的最大线程数
【发布时间】:2023-03-11 03:26:01
【问题描述】:

假设我有类似的东西:

def worker(name):
    time.sleep(10)
    print name
    return

thrs = []
for i in range(1000):
    t1 = threading.Thread(target=worker, args=(i,))
    thrs.append(t1)

for t in thrs:
    t.start()

有没有办法指定可以并行运行的线程数?在上述情况下,所有 1000 将并行运行

【问题讨论】:

  • threads.append(t1),我想是thrs.append(t1)吧?
  • 我没看懂这个问题...你已经指定了你想要的线程数:1000,如果你想要另一个数字,你不能改变这个吗?
  • @maxymoo 他们不确定有多少可能
  • 需要管理 CPU 和 RAM 进程。而for t in thrs: t.start()不是并行函数。
  • 我有 1000 件事情需要运行。但我希望他们一次运行 10 次或不运行。我想我可以运行然后加入并运行然后加入,直到没有更多的东西,但我试图看看是否有什么东西已经这样做了

标签: python multithreading python-2.7


【解决方案1】:

这可以使用multiprocessing.dummy 来完成,它提供了multiprocessing api 的线程版本。

from multiprocessing.dummy import Pool

pool = Pool(10)
result = pool.map(worker, range(1000))

在 python 3 中,concurrent.futures.ThreadPoolExecutor 通常会提供更好的界面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多