插播广告:2023年度人气创作者打榜中-帮我打榜吧~ https://activity.juejin.cn/rank/2023/writer/272334612598664?utm_campaign=annual_2023&utm_medium=self_web_share&utm_source=_%E5%B1%B1%E6%B5%B7
并行与并发的区别
官方文档: https://docs.python.org/zh-cn/3/library/concurrent.futures.html#module-concurrent.futures
# class concurrent.futures.Executor
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(pow, 323, 1235)
print(future.result())
submit 调度可调用对象fn
ThreadPoolExecutor 是 Executor 的子类,它使用线程池来异步执行调用。
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://nonexistant-subdomain.python.org/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
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)))
注意:当可调用对象已关联了一个 Future 然后在等待另一个 Future 的结果时就会导致死锁情况。
ProcessPoolExecutor是Executor 的子类,它使用进程池来异步地执行调用。
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ProcessPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()