[dmd-concurrency] Shutdown protocol
Michel Fortin
michel.fortin at michelf.com
Wed Jan 20 12:38:17 PST 2010
Le 2010-01-20 à 14:31, Andrei Alexandrescu a écrit :
> Good example. Is the interim conclusion to leave things as they are at least for the time being? I don't think they make things any more complicated than models that bring their own complications, and the current API does make a great deal of cases much simpler.
For the time being we could leave things as they are, but add the capability to manually call shutdown in a simple way. The example at the start of this thread would thus be rewritten like this, where I added "wait" in main and "scope (exit) tid.shutdown()" in copy:
import std.algorithm, std.concurrency, std.stdio;
void main() {
wait(
spawn(©("in1", "out1")),
spawn(©("in2", "out2"))
);
}
void copy(string input, string output) {
File source = File(input, "r");
enum bufferSize = 1024 * 100;
auto tid = spawn(&writer, outputPath); // Read loop
scope(exit) tid.shutdown();
foreach (immutable(ubyte)[] buffer; stdin.byChunk(bufferSize)) {
send(tid, buffer);
}
}
void writer(string output) {
File target = File(output, "w");
// Write loop
for (;;) {
auto buffer = receiveOnly!(immutable(ubyte)[])();
target.rawWrite(buffer);
}
}
The only thing worrying me a little is that it's easy to forget calling tid.shutdown() when an exception is thrown in the copy thread. It's really important to use of scope(exit) or some similar mechanism -- except in short demo programs like the one above unfortunately -- to avoid zombie threads.
I can't help but notice that the code above is quite like manual memory management, except with threads. Perhaps what we need is a GC for unreferenced threads...
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the dmd-concurrency
mailing list