我来看一下:http :
//www.chiark.greenend.org.uk/~sgtatham/coroutines.html,它非常有趣,应该提供一个不错的起点。但是我们当然使用Java,所以我们可以做得更好(或者可能更糟,因为没有宏:))
根据我对协程的了解,您通常会有一个 生产者 和一个 消费者
协程(或者至少这是最常见的模式)。但是从语义上讲,您不希望生产者致电消费者,反之亦然,因为这会引入不对称性。但是考虑到基于堆栈的语言的工作方式,我们将需要有人来进行调用。
因此,这是一个非常简单的类型层次结构:
public interface CoroutineProducer<T>{ public T Produce(); public boolean isDone();}public interface CoroutineConsumer<T>{ public void Consume(T t);}public class CoroutineManager{ public static Execute<T>(CoroutineProducer<T> prod, CoroutineConsumer<T> con) { while(!prod.IsDone()) // really simple { T d = prod.Produce(); con.Consume(d); } }}当然,现在最困难的部分是 实现 接口,特别是很难将计算分为几个步骤。为此,您可能需要其他整套 持久控制结构
。基本思想是我们要模拟控件的非本地传递(最后,它有点像在模拟
goto)。我们基本上希望
pc通过将当前操作的状态保留在堆中而不是堆栈中来摆脱使用堆栈和(程序计数器)的麻烦。因此,我们将需要一堆帮助程序类。
例如:
假设在一个理想的世界中,您想要编写一个看起来像这样的使用者(伪代码):
boolean is_done;int other_state;while(!is_done){ //read input //parse input //yield input to coroutine //update is_done and other_state;}我们需要抽象局部变量like
is_done和
other_state,并且需要抽象while循环本身,因为我们的
yieldlike操作不会使用堆栈。因此,让我们创建一个while循环抽象和相关类:
enum WhileState {BREAK, CONTINUE, YIELD}abstract class WhileLoop<T>{ private boolean is_done; public boolean isDone() { return is_done;} private T rval; public T getReturnValue() {return rval;} protected void setReturnValue(T val) { rval = val; } public T loop() { while(true) { WhileState state = execute(); if(state == WhileState.YIELD) return getReturnValue(); else if(state == WhileState.BREAK) { is_done = true; return null; } } } protected abstract WhileState execute();}这里的基本技巧是将 局部 变量移动为 类 变量,并将作用域块转换为类,这使我们能够在产生返回值之后“重新输入”“循环”。
现在实施我们的生产者
public class SampleProducer : CoroutineProducer<Object>{ private WhileLoop<Object> loop;//our control structures become state!! public SampleProducer() { loop = new WhileLoop() { private int other_state;//our local variables become state of the control structure protected WhileState execute() { //this implements a single iteration of the loop if(is_done) return WhileState.BREAK; //read input //parse input Object calcluated_value = ...; //update is_done, figure out if we want to continue setReturnValue(calculated_value); return WhileState.YIELD; } }; } public Object Produce() { Object val = loop.loop(); return val; } public boolean isDone() { //we are done when the loop has exited return loop.isDone(); }}对于其他基本控制流结构,可以采取类似的技巧。理想情况下,您将建立一个包含这些帮助程序类的库,然后使用它们来实现这些简单的接口,这些接口最终将为您提供协同例程的语义。我确信我在这里编写的所有内容都可以得到概括和扩展。



