Commit 6c47a5ed authored by Xavier Thompson's avatar Xavier Thompson

examples/: Add programs illustrating fork overloads

parent a2ff3992
#include <typon/typon.hpp>
#include <typon/logger.hpp>
using namespace typon;
int fibo(int n) {
if (n < 2)
return n;
return fibo(n - 1) + fibo(n - 2);
}
Task<int> hello(int n) {
int r = fibo(30);
LOG("hello(%d)", n);
co_return r;
}
Join<void> parallel() {
LOG("Forked f = co_await fork(hello(10))");
Forked f = co_await fork(hello(1));
LOG("co_await fork(hello(10), {})");
co_await fork(hello(2), {});
// Careful! r must not be unwound before the fork finishes.
LOG("int r; co_await fork(hello(10), r)");
int r; co_await fork(hello(3), r);
// Sync to ensure the fork finished before r is unwound.
// Assuming there are no exceptions...
co_await Sync();
}
Root root() {
co_await parallel();
}
int main() {
root().call();
puts("done");
return 0;
}
#include <typon/typon.hpp>
#include <cstdio>
using namespace typon;
Join<int> fibo(int n) {
if (n < 2) {
co_return n;
}
// Danger !
// The memory for a and b could be freed before the forks complete
int a; co_await fork(fibo(n - 1), a);
int b; co_await fork(fibo(n - 2), b);
// This sync() ensures that the forks complete before a and b are freed
// As long as there are no exceptions...
co_await Sync();
co_return a + b;
}
Root root() {
int result = co_await fibo(40);
printf("%d\n", result);
}
int main() {
root().call();
puts("done");
return 0;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment