Coroutines, can they slice and dice easier?

Richard Andrew Cattermole (Rikki) richard at cattermole.co.nz
Sat Nov 30 07:44:01 UTC 2024


To everyone who thinks that I have forgotten about coroutines, I 
have some good news for you!
They are still actively on my radar even if I'm not doing DIP 
writing work right now.

The current solution I have described is to produce a state 
machine with each transition having its own function. However 
this does give me concern about implementability given Walter's 
troubles with opApply.

What this is doing is producing a jump table that you are 
responsible for calling the appropriate function for. That'll 
work fine, but we can do better.

There is an optimization called [branch 
table](https://en.wikipedia.org/wiki/Branch_table), it is 
available in some languages such as C quite explicitly. But D has 
switch statements and that's basically the same thing right?

As it turns out it is exactly how integeral switches are 
implemented in dmd and ldc (without optimizations).

```d
int usesBranchTable(ubyte i) {
     switch(i) {
         static foreach(j; 0 .. 256) {
             case j:
             	return j;
         }

         default:
         	assert(0);
     }
}
```

What this means is that a coroutine handler function can be a 
single function of the signature:

```d
void handle(ref State);
```

Just the one function, should be easy to slice and dice for and 
add case statements for dynamically. Due to cross threading 
behavior of coroutines, and the thrashing of the CPU for a large 
quantity of them, the cases do not need to be sequential.

```d
case 0:

case 4: // injected later on

case 1:
case 2:
case 3:
```

The benefit of sequential numbers is that it limits jumping 
around in memory which isn't an issue here.

How cool is this?


More information about the Digitalmars-d mailing list