Can someone give me a little program design advice please?
Sean Kelly
sean at invisibleduck.org
Wed Jun 19 11:46:44 PDT 2013
On Jun 16, 2013, at 8:27 AM, Gary Willoughby <dev at kalekold.net> wrote:
> I'm writing a little program in D to perform some database operations and have a small question about design.
>
> Part of my program watches a log file for changes and this involves code which is wrapped up in a class. So the usage is something like this:
>
> auto fileWatcher = new FileWatcher(fileName);
> fileWatcher.onChange(delegate);
> fileWatcher.start();
>
> Once the start method is called a loop is entered within the class and the file is watched. Changes are handle through calling the registered delegate. The loop uses different watch methods for different platforms.
>
> What i need to be able to do is to stop the current watch and change the watched file.
>
> Because this is in an infinite loop, i can't check externally i.e. outside of the class, if i need to break from the loop simply because control never returns to the caller of the start() method.
>
> Am i missing something simple here? Any advice is welcome. I thought about threading and message passing but that's maybe overkill for something as simple as this?
Some form of concurrency is probably what you want here. But be aware that your delegate may have to be made thread-safe, depending on what it does. Regan suggested using Thread, and you can use spawn as well:
import std.concurrency;
import std.conv;
import std.datetime;
import std.stdio;
import core.thread;
void main()
{
auto tid = spawn(&fileWatcher, "file0");
foreach (i; 1 .. 5)
{
Thread.sleep(dur!"msecs"(300)); // sleep for a bit to simulate work
send(tid, "file" ~ to!string(i));
}
}
void fileWatcher(string fileName)
{
while (true)
{
receiveTimeout(dur!"msecs"(0),
(string n) => fileName = n);
writefln("checking %s", fileName);
Thread.sleep(dur!"msecs"(100)); // sleep for a bit to simulate work
}
writeln("bye!");
}
More information about the Digitalmars-d-learn
mailing list