Factories

A convenient programming construct is the co-routine, which is specified as an ordinary function, but maintains its own state between calls, and permits re-entry other than by the first statement.

The random generator example is used to illustrate its definition and use.

```     factory random(seed:int,limit:int):int;
rnd:=seed;
lim:= limit;
barrier lim;
leave lim:= lim-1;
rnd:= rnd*125;
yield rnd:= rnd % 32676;
redo lim;
exit lim;
end random;
```

The first time this factory is called, a plant is created in the local system to handle the requests. The plant contains the stack frame and synchronizes access.

In this case it initializes the generator. The random number is generated and yield as a result of the call. The factory plant is then put to sleep. The second call received by the factory wakes it up at the point where it went to sleep. In this case it will find a redo statement and produces the next random number. Note that also in this case a seed and limit value are expected, but they are ignored in the body. This factory can be called upon to generate at most 'limit' random numbers using the 'seed' to initialize the generator. Thereafter it is being removed, i.e. reset to the original state.

A cooperative group of factories can be readily constructed. For example, assume we would like the random factories to respond to both random(seed,limit) and random(). This can be defined as follows:

```     factory random(seed:int,limit:int):int;
rnd:=seed;
lim:= limit;
barrier lim;
leave lim:= lim-1;
rnd:= rnd*125;
yield rnd:= rnd % 32676;
redo lim;
exit lim;
end random;

factory random():int;
barrier forever:=true;
yield random(0,0);
redo forever;
exit forever;
end random;
```