[Haskell-cafe] Re: how to implement daemon start and stop directives?

Luke Palmer lrpalmer at gmail.com
Thu Jan 22 11:41:09 EST 2009


On Thu, Jan 22, 2009 at 9:04 AM, Ertugrul Soeylemez <es at ertes.de> wrote:

> > A program that needs only IORefs and is threadsafe is *good* style to
> > me, because it means all the state is well-encapsulated (if it
> > escaped, it would fail to be threadsafe).
>
> That's not my point.  The use of IORefs indicates an imperative
> programming style.


Um, we were talking about IORefs vs. MVars or TVars.  I thought we were
already firmly in the imperative world.  Nobody on this list will argue
against a pure solution always being preferable.


>  Sometimes this is inevitable, but I've never seen a
> case, where IORefs couldn't be replaced by a more elegant
> State/StateT-based solution.  And if you need to do multi-threading,
> Chans, MVars and semaphores are better anyway.


Please define "better".  For the function in question, what advantages do
they give us?

Just to be clear, I wouldn't dare argue that IORefs can do everything MVars
and TVars can do.   I'm just perplexed why you say MVars and TVars are
better, when an IORef does the trick just fine for our function.




There is no reason to
> prefer an IORef over an MVar to signal something to another thread.


Well, I usually don't go here, but benchmarks show that IORefs are the
fastest of any of the mutable variable primitives, by at least a factor of
2.  I wish I remembered where I saw that.


> By the way, IORefs are by themselves not thread-safe.  You need to use a
> special function, when using it in a multi-threaded manner.


You mean atomicModifyIORef?

IORefs *are* thread-safe by themselves: you will not make your program
segfault by using them in a multithreaded program.  So it all comes down to
invariants.  IORefs have no synchronization concepts, so code like:

    x <- readIORef ref
    writeIORef ref (x+1)

Is not threadsafe by most standards.  That doesn't mean IORefs themselves
are not threadsafe, just that you have to be careful how you use them.

And I will reiterate:  *in this case* the use of IORef is fully encapsulated
in this function and *is threadsafe!*  Which is the basis of my argument: in
imperative code, when you can limit the scope of an IORef to a small
abstraction that is threadsafe, there is no advantage of TVars or MVars over
them.  I don't think they deserve "bad style" sledgehammer.  (An instance of
"use the right tool for the job")

daemon :: IO () -> IO (IO ())
daemon action = do
    stopvar <- newIORef False
    let run = do
          stop <- readIORef stopvar
          if stop then return () else (action >> run)
    forkIO run
    return (writeIORef stopvar True)

Luke
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090122/51bb14a8/attachment.htm


More information about the Haskell-Cafe mailing list