
Hello Belka, Sunday, September 13, 2009, 10:45:35 AM, you wrote: i suggest you to use IORef Bool instead - as it was said once by SimonM, it's safe to use in m/t environment, of course without all fancy features of MVar locking if you need to be as fast as possible, IOUArray (1,1) may be used - this avoids boxing (array of one element is equivalent to IOURef type lacking in std libs)
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
-- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com