
Luke Palmer
On Thu, Jan 22, 2009 at 5:48 AM, Ertugrul Soeylemez
wrote: Luke Palmer
wrote: TVars are overkill here, actually, an IORef would be just fine, I think.
Using IORefs is generally a sign of bad style.
I totally disagree.
The disadvantage of IORefs is that they do not work together very nicely. If you have more than one, it is very hard (impossible) to keep multithreaded invariants between them.
But in this case, the IORef is completely encapsulated: it does not leave the scope in which it was created. You will never have to use it with any other IORef, because nobody else even knows it exists. The pattern is self-contained and threadsafe with just an IORef.
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. 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. There is no reason to prefer an IORef over an MVar to signal something to another thread. 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. Greets, Ertugrul. -- nightmare = unsafePerformIO (getWrongWife >>= sex) http://blog.ertes.de/