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相關內(nèi)容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
玩轉串口通信:利用pyserial庫,Python打開無限可能
想要學習如何使用pyserial庫實現(xiàn)串口通信嗎?這篇指南將帶你一步步了解Python中的串口通信,無論是控制硬件設備還是與外部設備進行數(shù)據(jù)交換,pyserial庫都能為你提供便捷的解決方案,快來跟著我們的指南,輕松掌握串口通信的技巧吧!2023-11-11
理解生產(chǎn)者消費者模型及在Python編程中的運用實例
生產(chǎn)者消費者模型一般用于體現(xiàn)程序的多線程并發(fā)性,Python的多線程雖然受到GIL控制,但依然可以構建隊列來簡單體現(xiàn)出模型的思路,這里我們就來共同理解生產(chǎn)者消費者模型及在Python編程中的運用實例:2016-06-06

