How can I use threading in Python?

前端 未结 19 2675
迷失自我
迷失自我 2020-11-21 04:54

I am trying to understand threading in Python. I\'ve looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I\'m having trou

19条回答
  •  别跟我提以往
    2020-11-21 05:12

    With borrowing from this post we know about choosing between the multithreading, multiprocessing, and async/asyncio and their usage.

    Python 3 has a new built-in library in order to concurrency and parallelism: concurrent.futures

    So I'll demonstrate through an experiment to run four tasks (i.e. .sleep() method) by Threading-Pool:

    from concurrent.futures import ThreadPoolExecutor, as_completed
    from time import sleep, time
    
    def concurrent(max_worker):
        futures = []
        tic = time()
        with ThreadPoolExecutor(max_workers=max_worker) as executor:
            futures.append(executor.submit(sleep, 2))  # Two seconds sleep
            futures.append(executor.submit(sleep, 1))
            futures.append(executor.submit(sleep, 7))
            futures.append(executor.submit(sleep, 3))
            for future in as_completed(futures):
                if future.result() is not None:
                    print(future.result())
        print(f'Total elapsed time by {max_worker} workers:', time()-tic)
    
    concurrent(5)
    concurrent(4)
    concurrent(3)
    concurrent(2)
    concurrent(1)
    

    Output:

    Total elapsed time by 5 workers: 7.007831811904907
    Total elapsed time by 4 workers: 7.007944107055664
    Total elapsed time by 3 workers: 7.003149509429932
    Total elapsed time by 2 workers: 8.004627466201782
    Total elapsed time by 1 workers: 13.013478994369507
    

    [NOTE]:

    • As you can see in the above results, the best case was 3 workers for those four tasks.
    • If you have a process task instead of I/O bound or blocking (multiprocessing vs threading) you could change the ThreadPoolExecutor to ProcessPoolExecutor.

提交回复
热议问题