程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python多線程與線程池常見核心用法

編輯:Python

一、線程池用法示例:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : 線程池核心代碼.py
# Author: DaShenHan&道長-----先苦後甜,任憑晚風拂柳顏------
# Date : 2021-03-25
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor(max_workers=20) # 初始化線程池內線程數量為20
if __name__ == '__main__':
obj = [pool.submit(print, i) for i in range(20)] # 構造一個列表,循環向線程池內submit提交執行的方法如print,不定長參數,這裡傳一個數字 i
pool.shutdown(wait=True) # 線程數等待所有線程結束,這裡 卡住主線程
print(obj) # 打印最後線程池內的結果

二、多線程用法示例:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : 多線程核心代碼.py
# Author: DaShenHan&道長-----先苦後甜,任憑晚風拂柳顏------
# Date : 2021-03-25
import threading
from threading import Thread
from time import sleep
from threading import enumerate
def thread_it(func,*args):
t = Thread(target=func,args=args)
t.setDaemon(True)
t.start()
def log(*args):
sleep(1)
print(args)
sleep(3)
def thread_over():
"""
檢測所有子線程是否執行完畢,返回true或者fasle
:return:
"""
for thread in enumerate():
if isinstance(thread,threading.Thread) and not isinstance(thread,threading._MainThread):
return False
return True
if __name__ == '__main__':
for i in range(20):
thread_it(log, '當前數字:',i)
while True:
sleep(2)
if thread_over():
break

三、異步加線程池

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : 多線程測試.py
# Author: DaShenHan&道長-----先苦後甜,任憑晚風拂柳顏------
# Date : 2021-03-25
from threading import Thread
from time import sleep
import requests
from concurrent.futures import ThreadPoolExecutor
import asyncio
pool = ThreadPoolExecutor(max_workers=20)
def thread_it(func,*args): # 注意,不定長任意參數是*args,只有一個*,不是兩個
t = Thread(target=func,args=args)
t.setDaemon(True)
t.start()
def log(txt):
sleep(0.5)
print(txt)
async def fetch(url):
res = await loop.run_in_executor(pool, requests.get, url)
return res.text
if __name__ == '__main__':
urls = ['baidu','mudery']
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([fetch(url) for url in urls]))

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved