Python 线程池用法简单示例

yipeiwu_com6年前Python基础

本文实例讲述了Python 线程池用法。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#! python3
'''
Created on 2019-10-2
@author: Administrator
'''
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
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=ProcessPoolExecutor(max_workers=3)
  futures=[]
  for i in range(11):
    future=executor.submit(task,i)
    futures.append(future)
  executor.shutdown(True)
  print('+++>')
  for future in futures:
    print(future.result())

运行结果:

38704 is runing
38704 is runing
38704 is runing
38696 is runing
38696 is runing
38696 is runing
38696 is runing
38696 is runing
38712 is runing
38712 is runing
38712 is runing
+++>
0
1
4
9
16
25
36
49
64
81
100

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python 多线程中子线程和主线程相互通信方法

需求:主线程开启了多个线程去干活,每个线程需要完成的时间不同,但是在干完活以后都要通知给主线程 下面上代码: #!/usr/bin/python # coding:utf8 '''...

Python编程对列表中字典元素进行排序的方法详解

本文实例讲述了Python编程对列表中字典元素进行排序的方法。分享给大家供大家参考,具体如下: 内容目录: 1. 问题起源 2. 对列表中的字典元素排序 3. 对json进行比较(忽略列...

Python3读取zip文件信息的方法

本文实例讲述了Python3读取zip文件信息的方法。分享给大家供大家参考。具体实现方法如下: 该程序接受一个字符串,其内容是一个zip文件,需要读取这个zip文件中的信息 ...

Flask SQLAlchemy一对一,一对多的使用方法实践

Flask-SQLAlchemy安装和建表操作请参考这里。 复制代码 代码如下:# Role表class Role(db.Model):    id=db...

python之文件读取一行一行的方法

如下所示: f=file('a.txt') for eachline in f: print eachline 以上这篇python之文件读取一行一行的方法就是小编分享给大家的...