Python [2]

多线程、多进程、协程

Posted by ZYT on November 19, 2018

多线程

from concurrent.futures import ThreadPoolExecutor
from time import time

def gcd(pair):
    a, b = pair
    low = min(a, b)
    for i in range(low, 0, -1):
        if a % i == 0 and b % i == 0:
            return i

numbers = [(1963309, 2265973), (2030677, 3814172),
           (1551645, 2229620), (2039045, 2020802)]

start = time()
pool = ThreadPoolExecutor(max_workers=2)
results = list(pool.map(gcd, numbers))
end = time()
print("Took %.3f seconds" % (end - start))

"""
Took 0.477 seconds
"""

多进程

from concurrent.futures import ProcessPoolExecutor
from time import time

def gcd(pair):
    a, b = pair
    low = min(a, b)
    for i in range(low, 0, -1):
        if a % i == 0 and b % i == 0:
            return i

numbers = [(1963309, 2265973), (2030677, 3814172),
           (1551645, 2229620), (2039045, 2020802)]

start = time()
pool = ProcessPoolExecutor(max_workers=2)
results = list(pool.map(gcd, numbers))
end = time()
print("Took %.3f seconds" % (end - start))

"""
Took 0.265 seconds
"""

协程

import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

"""
Compute 1 + 2 ...
1 + 2 = 3
"""

Python Asyncio

yield from

yield from 等价于 for item in iterable: yield item

>>> def g(x):
...     yield from range(x, 0, -1)
...
>>> list(g(5))
[5, 4, 3, 2, 1]