Python中为什么要使用线程池?如何使用线程池?

  系统处理任务时,需要为每个请求创建和销毁对象.当有大量并发任务需要处理时,再使用传统的多线程就会造成大量的资源创建销毁导致服务器效率的下降.这时候,线程池就派上用场了.线程池技术为线程创建、销毁的开销问题和系统资源不足问题提供了很好的解决方案.

from concurrent.futures import ThreadPoolExecutor
import os, time, random

def task(n):
    print('%s is runing' % os.getpid())
    time.sleep(random.randint(1, 3))
    return n ** 2

if __name__ == '__main__':
    executor = ThreadPoolExecutor(max_workers=3)
    executor.map(task, range(1, 7))

猜你喜欢

转载自www.cnblogs.com/apollo1616/p/10206009.html
今日推荐