在python中一次只能运行5个线程

2024-09-25 00:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含日期列表的文本文件。我想将每个日期作为参数传递给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(这是文件中所有日期项的数目)。在


Tags: 文件importself脚本timeinitdefsleep
2条回答

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

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

(流程池的示例就在文档的开头。如果您真的认为您需要一个线程池,语法应该是相同的-只需将multiprocessing替换为^{}

在确定需要线程而不是进程的情况下,可以使用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库才能正常工作:

^{pr2}$

相关问题 更多 >