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]))