【问题标题】:python how to set a thread limit?python如何设置线程限制?
【发布时间】:2017-01-21 15:20:37
【问题描述】:

我想知道如何限制这样的事情一次只使用 10 个线程

with open("data.txt") as f:
    for line in f:
        lines = line.rstrip("\n\r")
        t1 = Thread(target=Checker, args=("company"))
        t1.start()

【问题讨论】:

标签: python multithreading


【解决方案1】:

使用 Python 的 ThreadPoolExecutor 并将 max_workers 参数设置为 10。

类似这样的:`

pool = ThreadPoolExecutor(max_workers=10)
with open("data.txt") as f:
    for line in f:
        lines = line.rstrip("\n\r")
        pool.submit(Checker,"company")

pool.shutdown(wait=True)

pool 会根据需要自动分配线程,将最大分配数限制为 10。pool.submit() 中的第一个参数是函数名,参数只是以逗号分隔的值传递。

pool.shutdown(wait=True) 等待所有线程完成执行。

【讨论】:

    【解决方案2】:

    使用ThreadPoolExecutor 并告诉它您想要10 个线程。

    def your_function_processing_one_line(line):
        pass  # your computations
    
    with concurrent.futures.ThreadPoolExecutor(10) as executor:
        result = executor.map(your_function_processing_one_line, [line for line in f])
    

    ...您将在result 中获得所有结果。

    【讨论】:

    • 如果有多个参数怎么办?
    • 这也是可能的。看看this nice answer
    【解决方案3】:

    我编写了这个嵌套循环来将线程限制为一个变量。 此代码依赖于一组预设的命令来处理。 我从其他答案中借用了一些元素来启动线程。

    import os, sys, datetime, logging, thread, threading, time
    from random import randint
    
    # set number of threads
    threadcount = 20
    
    # alltests is an array of test data
    
    numbertests = len(alltests)
    testcounter = numbertests
    
    # run tests
    for test in alltests:
        # launch worker thread
        def worker():
            """thread worker function"""
            os.system(command)
            return
        threads = []
        t = threading.Thread(target=worker)
        threads.append(t)
        t.start()
        testcounter -= 1
        # cap the threads if over limit
        while threading.active_count() >= threadcount:
            threads = threading.active_count()
            string = "Excessive threads, pausing 5 secs - " + str(threads) 
            print (string)
            logging.info(string)
            time.sleep(5)
    
    # monitor for threads winding down
    while threading.active_count() != 1:
        threads = threading.active_count()
        string = "Active threads running - " + str(threads) 
        print (string)
        logging.info(string)
        time.sleep(5)
    

    【讨论】:

      【解决方案4】:

      (适用于 Python 2.6+ 和 Python 3)

      使用来自multiprocessing 模块的threadPool

      from multiprocessing.pool import ThreadPool
      

      唯一的问题是它没有很好的记录......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-13
        • 2023-03-15
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        • 2016-06-03
        • 2016-08-25
        • 1970-01-01
        相关资源
        最近更新 更多