yield是什么

In computer science, yield is an action that occurs in a computer program during multithreading, of forcing a processor to relinquish control of the current running thread, and sending it to the end of the running queue, of the same scheduling priority.

引自维基百科:Yield (multithreading)),中文译文:

在计算机科学中,yield是发生在多线程程序中的一种情形:强制让处理器放弃对当前运行线程的控制,并把它发送到运行队列的尾部。(队列中的线程拥有相同的运行优先级)

关键字:放弃对线程的控制

generator是什么

In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop. In fact, all generators are iterators.[1] A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

引自维基百科:Generator (computer programming))

出发点:为了节省内存。关键字:看起来像函数,行为像迭代器。

Python中的generator

Python中的generator需要借助于yield实现

  1. def countfrom(n):
  2. while True:
  3. yield n
  4. n += 1

yield细节

基础用法

  1. def countfrom(n):
  2. while True:
  3. yield n # 返回n,等待下一次取数,即”放弃线程控制权“
  4. n += 1

接受输入

  1. def countfrom(n):
  2. x = 'start'
  3. while True:
  4. x = yield x # 第一次返回 start,后面接受输入到x,再返回x