yield学习笔记

参考:http://www.dabeaz.com/finalgenerator/

from concurrent.futures import ThreadPoolExecutor
import time
pool = ThreadPoolExecutor(max_workers=8)

def func(x, y):
    time.sleep(5)
    return x, y

def do_func(x, y):
    result = yield pool.submit(func, x, y)
    print('Got: ', result)
 
def after(delay, gen):
    yield pool.submit(time.sleep, delay)
    result = None
    try:
        while True:
            f = gen.send(result)
            result = yield f
    except StopIteration:
        print('after ecoutnered StopIteration.')
 
class Task:
    def __init__(self, gen):
        self._gen = gen
    def step(self, value=None):
        # Run to the next yield
        try:
            fut = self._gen.send(value)
            # Future returned
            fut.add_done_callback(self._wakeup)
        except StopIteration as exc:
            print('Task encountered StopIteration.')
    def _wakeup(self, fut):
        # handler for results
        result = fut.result()
        self.step(result)  # Feedback loop (run to next yield)

为查看完整图片,可右键单击图片选择在新页面中查看。

 

posted @ 2018-04-07 21:12  F君君  阅读(118)  评论(0编辑  收藏  举报