Python线程池详细操作教程
如果线程池中的线程完成其执行,则可以重用该线程。
如果某个线程终止,则将创建另一个线程来替换该线程。
ThreadPoolExecutor
ProcessPoolExecutor
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
from concurrent.futures import ThreadPoolExecutor
from time import sleep
def task(message):
sleep(2)
return message
def main():
executor = ThreadPoolExecutor(5)
future = executor.submit(task, ("Completed"))
print(future.done())
sleep(2)
print(future.done())
print(future.result())
if __name__ == '__main__':
main()
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
False
True
Completed
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
with ThreadPoolExecutor(max_workers = 5) as executor
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout = timeout) as conn:
return conn.read()
with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor:
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>
'http://www.foxnews.com/' page is 229313 bytes
'http://www.cnn.com/' page is 168933 bytes
'http://www.bbc.co.uk/' page is 283893 bytes
'http://europe.wsj.com/' page is 938109 bytes
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
values = [2,3,4,5]
def square(n):
return n * n
def main():
with ThreadPoolExecutor(max_workers = 3) as executor:
results = executor.map(square, values)
for result in results:
print(result)
if __name__ == '__main__':
main()
# Filename : example.py
# Copyright : 2020 By Bianchenghao6
# Author by : bianchenghao6.com
# Date : 2020-08-22
4
9
16
25