import std.stdio;
import core.thread;
import std.datetime; // for stopwatch
import std.parallelism;
void say(string s) { // write and flush
writeln(s);
stdout.flush();
}
struct Dish {
string name;
void prepare() {
say("Start with the " ~ name ~ ".");
Thread.sleep(1.seconds); // kunstmatig tijd verbruiken
say("Finished the " ~ name ~ ".");
}
}
void main() {
auto dishes = [ Dish("soup"), Dish("sauce"), Dish("fries"),
Dish("fish"), Dish("ice") ];
auto sw = StopWatch(AutoStart.yes);
foreach (dish; parallel(dishes, 1)) dish.prepare();
sw.stop;
writefln("Diner is ready. Cooking took %.3f seconds.",
cast(float) sw.peek.msecs / 1000);
}
gives:
Start with the soup.
Start with the sauce.
Start with the fries.
Start with the fish.
Finished the sauce.
Finished the fries.
Start with the ice.
Finished the soup.
Finished the fish.
Finished the ice.
Diner is ready. Cooking took 1.999 seconds.
Seems that 4 cores go all out on first 4 dishes, then 1 core
deals with the last dish. With 4 cores I expect diner is ready
after 5/4 = 1.25 secs though. What did I do wrong?