Threading challenge: calculate fib(45) while spinning
Ali Çehreli
acehreli at yahoo.com
Fri Oct 15 03:54:17 UTC 2021
On 10/14/21 8:35 PM, jfondren wrote:
> The book, "The Go Programming Language" has this simple goroutine example:
Here is one that uses receiveTimeout and OwnerTerminated:
import std.stdio;
import std.concurrency;
import core.thread;
void main() {
spawnLinked(&spinner, 100.msecs);
enum n = 45;
const fibN = fib(n); // slow
writefln!"\rFibonacci(%d) = %d"(n, fibN);
}
void spinner(const(Duration) delay) {
for (;;) {
foreach (r; `-\|/`) {
writef!"\r%c"(r);
stdout.flush();
bool done;
receiveTimeout(delay,
(OwnerTerminated msg) {
done = true;
});
if (done) {
return;
}
}
}
}
auto fib(int x) {
if (x < 2) {
return x;
}
return fib(x-1) + fib(x-2);
}
Ali
More information about the Digitalmars-d-learn
mailing list