【问题标题】:Run 5 Threads only at a Time in python在python中一次只运行5个线程
【发布时间】:2019-10-30 05:54:57
【问题描述】:

我有一个包含日期列表的文本文件。我想将每个日期作为参数传递给 shell 脚本,并为文件中的所有指定日期运行脚本。

我想使用 python 并行执行这个任务。由于脚本具有复杂的逻辑并且要监视执行,我想一次运行 5 个实例。一旦脚本完成,python 必须启动新线程。

import threading
import time


class mythread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.h = i
        # Script will call the function

    def run(self):
        time.sleep(1)
        print("Value send ", self.h)


f = open('C:\Senthil\SenStudy\Python\Date.txt').readlines()
num = threading.activeCount()

for i in f:
    print("Active threads are ", num)
    time.sleep(1)
    if threading.activeCount() <= 5:
        thread1 = mythread(i)
        thread1.start()
    else:
        print("Number of Threads are More than 5 .. going to sleep state for 1 mint ...")
        time.sleep(1)

我尝试使用threading.activeCount() 来获取正在运行的线程数,但从一开始它就说线程数是 30(这是文件中所有日期条目的数量)。

【问题讨论】:

标签: python


【解决方案1】:

如果你确定你需要线程而不是进程,你可以使用ThreadPoolExecutor 运行固定数量的工作线程来完成这项工作:

from concurrent.futures import ThreadPoolExecutor


DATE_FILE = 'dates.txt'
WORKERS = 5


def process_date(date):
    print('Start processing', date)

    # Put here your complex logic.

    print('Finish processing', date)


def main():

    with open(DATE_FILE) as date_file:
        dates = [line.rstrip() for line in date_file]

    with ThreadPoolExecutor(WORKERS) as executor:
        executor.map(process_date, dates)
        executor.shutdown()


if __name__ == '__main__':
    main()

如果您使用 Python 2,则必须先安装 futures 库才能使其正常工作:

pip install --user futures

【讨论】:

    【解决方案2】:

    您的问题似乎是为 python 进程池或线程池量身定制的。如果每个“线程”的输入参数只是一个日期,我认为进程池可能会更好,因为线程之间的同步可能会很棘手。

    请阅读documentation 中的multiprocessing 模块,看看它是否能解决您的问题。如果您对此有任何疑问,我很乐意澄清。

    (一个进程池的例子就在文档的开头。如果你真的认为你需要一个线程池,语法是一样的 --- 只需将 multiprocessing 替换为 multiprocessing.dummy。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多