1. 程式人生 > 程式設計 >Python 執行緒池用法簡單示例

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程式設計有所幫助。