• 进程池与线程池(concurrent.futures)


     1 from concurrent.futures import ProcessPoolExecutor
     2 import os,time,random
     3 def task(n):
     4     print('%s is running'%os.getpid())
     5     time.sleep(random.randint(1,2))
     6     return n**2
     7 if __name__ == '__main__':
     8     p = ProcessPoolExecutor()     #默认开启四个进程池
     9     l = []
    10     start = time.time()
    11     for i in range(10):
    12         obj = p.submit(task,i)
    13         l.append(obj)
    14     p.shutdown()
    15     print('='*30)
    16     print([obj for obj in l])
    17     print(time.time() - start)
    进程池
     1 from concurrent.futures import ThreadPoolExecutor
     2 import threading
     3 import os,time,random
     4 def task(n):
     5     print('%s:%s is running'%(threading.currentThread().getName(),os.getpid()))
     6     time.sleep(random.randint(1,2))
     7     return n**2
     8 if __name__ == '__main__':
     9     t = ThreadPoolExecutor()
    10     l = []
    11     start = time.time()
    12     for i in range(10):
    13         obj = t.submit(task,i)
    14         l.append(obj)
    15     t.shutdown()
    16     print('='*30)
    17     print([obj.result() for obj in l])   #可以获取结果
    18     print(time.time() - start)
    线程池
     1 from concurrent.futures import ProcessPoolExecutor
     2 import os,time,random
     3 def task(n):
     4     print('%s is running'%os.getpid())
     5     time.sleep(1)
     6     return n**2
     7 if __name__ == '__main__':
     8     p = ProcessPoolExecutor()
     9     start = time.time()
    10     for i in range(10):
    11         res = p.submit(task,i).result()    #同步执行,速度较慢,一个等一个
    12         print(res)
    13     print('='*30)
    14     print(time.time() - start)
    补充
  • 相关阅读:
    第一个dubbo程序
    spring aop通过注解实现日志记录
    Java操作zookeeper
    VMware安装Linux并配置网络通信
    多线程工具之CompletionService
    Netty实现简易http_server
    python3.4 + Django1.7.7 表单的一些问题
    【编程练习】八大排序算法
    OpenCV特征点检测------Surf(特征点篇)
    Opencv学习笔记------Harris角点检测
  • 原文地址:https://www.cnblogs.com/52-qq/p/7458634.html
Copyright © 2020-2023  润新知