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中的decimal类型转换实例详解

[Python标准库]decimal——定点数和浮点数的数学运算         作用:使用定点数和浮点数的小数运算...

Pycharm新手教程(只需要看这篇就够了)

Pycharm新手教程(只需要看这篇就够了)

pycharm是一款高效的python IDE工具,它非常强大,且可以跨平台,是新手首选工具!下面我给第一次使用这款软件的朋友做一个简单的使用教程,希望能给你带来帮助! 目前pycha...

python matplotlib画图实例代码分享

python matplotlib画图实例代码分享

python的matplotlib包支持我们画图,有点非常多,现学习如下。 首先要导入包,在以后的示例中默认已经导入这两个包 import matplotlib.pyplot as...

python如何在列表、字典中筛选数据

python如何在列表、字典中筛选数据? 实际问题有哪些? 1.过滤掉列表[3,9,-1,10.-2......] 中负数 2.筛选出字典 {‘li_ming':90,'xiao_hon...

python正则表达式的使用

python的正则是通过re模块的支持 匹配的3个函数 match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none; re.match(patt...