[Haskell-cafe] Using tiny (atomic) mutables between multiple threads

Belka lambda-belka at yandex.ru
Sun Sep 13 02:45:35 EDT 2009


Hello, Haskell Cafe!

I used an MVar to signalize to many threads, when it's time to finish their
business (I called it a LoopBreaker). Recently I realized, that it might be
too expensive (to use MVar) for cases when threads are many and all of them
read my LoopBreaker intensively. This assumption appeared in a case, where I
widely (in many threads) used my stopableThreadDelay, which checks
LoopBreaker every d = 100 milliseconds.

So I decided that I don't really need all the great features, that MVar
provides, and that a simpler memory usage concept might be applied here. In
a most (machinely) reduced view, all I need is a mutable byte. It would be
thread safe, since reading and writing are atomic operations. I then wrote a
simple experimental module (my first experience with Ptr in Haskell):
-----------------
import Control.Monad
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.Storable

newtype MyVar a = MyVar { mvPtr :: Ptr a }

newMyVar :: Storable a => a -> IO (MyVar a)
newMyVar val = MyVar `liftM` new val

readMyVar :: Storable a => (MyVar a) -> IO a
readMyVar val = peek $ mvPtr val

writeMyVar :: Storable a => (MyVar a) -> a -> IO ()
writeMyVar var val = poke (mvPtr var) val
-----------------

Now, please, help me to answer few questions about all it:
1. Might readMVar really be computationally expensive under heavy load,
(with all it's wonderful blocking features)? How much (approximately) more
expensive, comparing to a assembler's "mov"?
2. Are the above readMyVar and writeMyVar really atomic? Or are they atomic
only if I apply them to <MyVar Word8> type?
3. Are the above readMyVar and writeMyVar safe against asynchronous
exceptions? Or again, only if I use <MyVar Word8> type?

Belka
-- 
View this message in context: http://www.nabble.com/Using-tiny-%28atomic%29-mutables-between-multiple-threads-tp25420972p25420972.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.



More information about the Haskell-Cafe mailing list