Multithreading and Loggers
TheFlyingFiddle
theflyingfiddle at gmail.com
Sat Feb 1 13:41:45 PST 2014
On Friday, 31 January 2014 at 13:48:09 UTC, Nicolas F. wrote:
> Hello,
>
> I'm having some problems wrapping my head around shared classes
> and whatnot.
> So my application has a Logger class, which basically just
> writes formatted messages to a target, of which debugGLLogger
> inherits. What debugGLLogger does is simple in theory: it
> supplies a callback function to OpenGL, and said callback
> function uses a logger to write debug messages coming from
> OpenGL to.
>
> First off, I can't control the fact that it's a callback
> function, or when it is called, as this is done by the driver,
> windowing system, and so on.
>
> Hence, to know which logger I need to write to, I used a static
> variable which gets set to my main logger for OpenGL.
>
> In theory, this should work, as I'm currently (or so I thought)
> not using concurrency, which means that the static variable
> should exist in all cases.
>
> However, apparently the callback function is possibly called
> from a different thread which I have no control over, as I've
> had to painfully discover. My mainLogger static variable is
> useless, and everything falls apart. I'm not sure where this
> thread comes from, and maybe I'm just imagining things, but
> since I see no other way the variable could suddenly become
> null, I'm guessing that's the issue.
>
> So in some way I've got to bring the "shared" keyword into
> play, so I have a reference to a logger instance which I can
> use across threads. However, apparently for that, the class
> also needs to be shared, and I'm not sure if that's even the
> "right" way to do things.
>
> I've also thought that maybe I should utilise a seperate thread
> to run all loggers in, and communicate with the loggers through
> message-passing.
>
> I'm not an experienced programmer, so I'd love to hear some
> advice on how I could solve this.
You could always use __gshared instead of shared. Then it becomes
a global static variable and you don't have to deal with the
current shared mess. It comes with the canveat that it's not
safe. (as in not data-race safe)
More information about the Digitalmars-d
mailing list