# I'm using different count_to_n now, with a special case for the initial # value. Seems better. using namespace std use deque use stdio.h deque q typedef int (*process_func)(process *p) struct process process_func f int pc process(process_func f) : f(f), pc(1) . inline void start(process *p) q.push_back(p) inline bool resume(process *p) int rv = (*p->f)(p) if rv p->pc = rv return rv run() while !q.empty() step() step() process *p = q.front() q.pop_front() if resume(p) q.push_back(p) struct rendezvous process *waiting rendezvous() : waiting(NULL) . # here are the general rendezvous methods: # meet - if the partner is here, returns 0, # otherwise we wait for the partner to arrive, returns 1, # (caller must then yield) bool meet(process *p) bool must_wait = !waiting if must_wait waiting = p return must_wait # pass - give control to the partner # (this works whether or not they are here already) void pass(process *p) if waiting start(waiting) waiting = p # part - finish the rendezvous # (this assumes they are here) void part() start(waiting) waiting = NULL # peer - get the partner's process pointer # or NULL if they are not here process *peer() return waiting # here - check if the partner is here bool here() return peer() != NULL template struct channel : rendezvous T data struct count_to_three process p channel *out count_to_three(channel *out) : p(count_to_three_f), out(out) . int count_to_three_f(process *p) count_to_three *d = (count_to_three *)p switch p->pc 1 if d->out->meet(p) p->pc = 2 return 0 2 d->out->data = 1 d->out->part() if d->out->meet(p) p->pc = 3 return 0 3 d->out->data = 2 d->out->part() if d->out->meet(p) p->pc = 4 return 0 4 d->out->data = 3 d->out->part() return 0 struct printer process p channel *in printer(channel *in) : p(printer_f), in(in) . int printer_f(process *p) printer *d = (printer *)p switch p->pc 1 while 1 p->pc = 2 d->in->pass(p) return 0 2 printf("%d\n", d->in->data) return 0 struct count_to_n process p channel *out int n count_to_n(channel *out, int n) : p(count_to_n_f), out(out), n(n) . int count_to_n_f(process *p) count_to_n *d = (count_to_n *)p switch p->pc 1 if d->out->meet(p) p->pc = 2 return 0 2 d->out->data = 1 d->out->part() while d->out->data < d->n if d->out->meet(p) p->pc = 3 return 0 3 ++ (d->out->data) d->out->part() return 0 int main() channel ch count_to_three c3(&ch) printer pr(&ch) start(&c3.p) start(&pr.p) run() count_to_n cn(&ch, 15) start(&cn.p) run() return 0