event based timer
Martin Nowak
dawg at dawgfoto.de
Wed Jul 20 02:53:54 PDT 2011
You are aware though that in your timer, the callback is executed from
within a different thread.
You could let the timer thread send messages as clock ticks and wait on
them, that way risking less issues
with implicit sharing.
Martin
----
import std.concurrency, std.stdio;
import core.thread;
struct Timer {
private Tid clock;
private bool running;
enum Terminate { _ };
enum Ping { _ };
~this() {
stop();
}
void start(Duration duration) {
avoidMailboxSpam();
stop();
clock = spawnLinked(&runClock, thisTid, duration);
running = true;
}
void stop() {
if (running)
clock.send(Terminate._);
running = false;
}
void wait() {
receiveOnly!Ping();
}
private static void avoidMailboxSpam() {
setMaxMailboxSize(thisTid, 5, OnCrowding.throwException);
}
private static void runClock(Tid tick, Duration duration) {
bool cont = true;
size_t cnt;
try {
while (cont) {
auto timedOut = !receiveTimeout(
duration,
(Terminate) { cont = false; },
);
if (timedOut) {
writefln(" #%-5d Ping ", cnt++);
tick.send(Ping._);
}
}
} catch (Exception ex) {
stderr.writeln(ex.msg);
throw ex;
}
}
}
void main() {
Timer timer;
auto interval = dur!"msecs"(500);
timer.start(interval);
foreach(cnt; 0 .. 200) {
timer.wait();
// Play some pong, if it takes too long our mailbox gets flooded
Thread.sleep(interval / 2);
writefln(" Pong #%-5d", cnt);
}
timer.stop();
}
On Wed, 20 Jul 2011 09:34:39 +0200, maarten van damme
<maartenvd1994 at gmail.com> wrote:
> Thanks but it seems way more complex then I need, I tried writing my own
> but
> I get an acces violation error. here is my try :
> http://dl.dropbox.com/u/15024434/Timer.d . Can someone spot the error?
> keep
> in mind I don't really understand the threading model and pointers.
>
>
> 2011/7/19 Piotr Szturmaj <bncrbme at jadamspam.pl>
>
>> maarten van damme wrote:
>>
<snip>
>>
>> There is no callback timer in Phobos. But here's my implementation of
>> timer
>> wheel I used in one of my projects: http://pastebin.com/dRRZtPVW. Feel
>> free to use it if you want.
>>
More information about the Digitalmars-d
mailing list