Best Direction on Spawning Process Async
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Sep 16 00:21:36 PDT 2015
On 09/15/2015 09:21 PM, Mike McKee wrote:
> What's the best direction from...
>
> http://dlang.org/phobos/std_process.html
>
> ...on spawning an async process and then peeking at it occasionally as
> it runs, and then get notified when it finishes? In other words, what
> std.process functions would you recommend I use? What I want to avoid is
> a blocking state where the GUI freezes because it's waiting for the
> process to complete.
>
> For instance, imagine you are building a front end GUI (like GtkD) to a
> command-line based antivirus scanner. You'll want to spawn the process,
> show a progress bar, and as the command line returns status information,
> you peek at it asynchronously and then update the progress bar (or
> perhaps store virus detected info in a table), and then stop the
> progress bar at 100% when the command process has finished.
>
Sounds like an easy task for std.concurrency:
import std.stdio;
import std.concurrency;
import core.thread;
struct Progress {
int percent;
}
struct Done {
}
void doWork() {
foreach (percent; 0 .. 100) {
Thread.sleep(100.msecs);
if (!(percent % 10)) {
ownerTid.send(Progress(percent));
}
}
ownerTid.send(Done());
}
void main() {
auto worker = spawn(&doWork);
bool done = false;
while (!done) {
bool received = false;
while (!received) {
received = receiveTimeout(
// Zero timeout is a non-blocking message check
0.msecs,
(Progress message) {
writefln("%s%%", message.percent);
},
(Done message) {
writeln("Woohoo!");
done = true;
});
if (!received) {
// This is where we can do more work
Thread.sleep(42.msecs);
write(". ");
stdout.flush();
}
}
}
}
Ali
More information about the Digitalmars-d-learn
mailing list