Threading in Python for each item in list

前端 未结 1 890
余生分开走
余生分开走 2021-01-24 07:03

I have a list H = [item1, item2, item3....so on] and a function,

def start(item1):
    p1 = Do something to item1     
    return p1
相关标签:
1条回答
  • 2021-01-24 07:28

    Make a function which runs a given function in a thread and stores the result:

    import threading
    def run_item(f, item):
        result_info = [threading.Event(), None]
        def runit():
            result_info[1] = f(item)
            result_info[0].set()
        threading.Thread(target=runit).start()
        return result_info
    

    Then another function to gather the results:

    def gather_results(result_infos):
        results = [] 
        for i in xrange(len(result_infos)):
            result_infos[i][0].wait()
            results.append(result_infos[i][1])
        return results
    

    Then from the main thread, say proc is the function that processes an item and items is your list of items to process:

    #start processing the items
    result_infos = [run_item(proc, item) for item in items]
    #gather the results (blocking)
    results = gather_results(result_infos)
    

    Example usage:

    >>> import time
    >>> def proc(item):
    ...     time.sleep(2.0)
    ...     return item * 2
    ... 
    >>> print gather_results([run_item(proc, item) for item in [1, 2, 10, 100]])
    #2 seconds later...
    [2, 4, 20, 200]
    
    0 讨论(0)
提交回复
热议问题