【问题标题】:Start multiple threads given a list of parameters [duplicate]给定参数列表启动多个线程[重复]
【发布时间】:2017-03-26 05:04:34
【问题描述】:

假设我有一个将作为函数参数的字符串列表。

如何启动n 线程(n 是参数列表的长度),所有线程都执行相同的函数,每个函数都带有列表中的参数?

【问题讨论】:

  • 这太宽泛了。请注意,如果您想加快处理速度,线程将无济于事,因为 python 使用 GIL(全局解释器锁)。您必须改用多处理。
  • 嗯,但是,我该怎么做呢?

标签: python multithreading python-3.x pthreads


【解决方案1】:
import threading

single_params = ['param1', 'param2', 'param3']
threads = []
# f() will be a function that takes a single string parameter 

for p in single_params: 
    threads.append(threading.Thread(target=f, args=(p))

for thread in threads:
    thread.start()

【讨论】:

  • 你没有以任何方式提到线程
  • 是的。我假设你知道如何启动线程。如果没有,这应该会有所帮助docs.python.org/2/library/threading.html#threading.Thread
  • 你能说得更清楚点吗?我的意思是,我知道如何手动一个一个地启动线程,但是我可以用 for 循环自动化这个过程吗?
  • 哦,我现在明白了。让我更新
  • 我更新了它,但共识似乎是多处理是要走的路
猜你喜欢
  • 2014-02-03
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
相关资源
最近更新 更多