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

Common core usage of Python multithreading and thread pool

編輯:Python

One 、 Example of thread pool usage :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : Thread pool core code .py
# Author: DaShenHan& long ----- First bitter, then sweet , Let the evening wind blow the willow face ------
# Date : 2021-03-25
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor(max_workers=20) # The number of threads in the initialization thread pool is 20
if __name__ == '__main__':
obj = [pool.submit(print, i) for i in range(20)] # Construct a list , Loop to the thread pool submit The method of submission and execution is as follows print, Indefinite length parameter , Pass a number here i
pool.shutdown(wait=True) # Number of threads waiting for all threads to end , here Stuck main thread
print(obj) # Print the results in the last thread pool

Two 、 Examples of multithreading usage :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : Multithreaded core code .py
# Author: DaShenHan& long ----- First bitter, then sweet , Let the evening wind blow the willow face ------
# 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():
"""
Check whether all sub threads have completed execution , return true perhaps 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, ' Current number :',i)
while True:
sleep(2)
if thread_over():
break

3、 ... and 、 Asynchronous process pool

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : Multithreaded testing .py
# Author: DaShenHan& long ----- First bitter, then sweet , Let the evening wind blow the willow face ------
# 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): # Be careful , Any parameter of indefinite length is *args, only one *, Not two
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