Python并发编程

2023-12-24 14:28:49

插播广告: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


并行与并发的区别

  • 并发: 宏观上,多个任务同时运行; 一个CPU核心交替运行多个程序。
  • 并行: 同一时刻发生; 多个CPU同时处理多个程序。

concurrent库实现并行计算

官方文档: https://docs.python.org/zh-cn/3/library/concurrent.futures.html#module-concurrent.futures

Executor

# class concurrent.futures.Executor
with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())

submit 调度可调用对象fn

ThreadPoolExecutor

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

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

文章来源:https://blog.csdn.net/ringnian/article/details/135181386
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。