[Haskell-beginners] STM and IO

emmanuel.delaborde emmanuel.delaborde at cimex.com
Thu Apr 9 05:33:35 EDT 2009


Hello list

I am trying to use STM for shared access to a file

I first used a TVar to to accumulate the text returned by the threads
and write TVar's content to a file after a delay (how do you ensure  
all threads have terminated by the way, that would be more robust than  
using an arbitrary delay)


-- this works
main = do
     let fname = "store.txt"
     store <- atomically $ newTVar ""
     forkIO $ 10 `replicateM_` (thread store)
     threadDelay 800000
     txt <- atomically (readTVar store)
     writeFile fname txt

thread :: TVar (String) -> IO ()
thread store = atomically ( readTVar store >>= writeTVar store . (++ "  
some text "))


But when I try to concurrently write to the file, I get into troubles.
I keep the file handle in a TMVar, hoping than just one thread at a  
time will be able to use that handle
but nothing gets written to "store.txt" ? Is my IO too lazy ?


-- this does not work
main = do
    let fname = "store.txt"
    fh <- openFile fname ReadWriteMode
    store <- atomically $ newTMVar fh
    forkIO $ 10 `replicateM_` (writeTo store)

writeTo :: TMVar (Handle) -> IO ()
writeTo store = do
    fh <- atomically $ takeTMVar store
    text <- hGetContents fh
    hPutStr fh (text ++ " some text ")
    atomically $ putTMVar store fh


Thank you

--
Emmanuel Delaborde

-----------------------------------------------------------------------------------------------

This e-mail (and any attachments) is confidential and may contain 
personal views which are not the views of Cimex Media Ltd and 
any affiliated companies, unless specifically stated. It is intended 
for the use of the individual or group to whom it is addressed. If 
you have received it in error, please delete it from your system, 
do not use, copy or disclose the information in any way nor act in 
reliance on it and please notify postmaster at cimex.com

A company registered in England  Wales. Company Number 03765711
Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester,
Northants NN12 6DB

This email was scanned by Postini, the leading provider in Managed Email Security.



More information about the Beginners mailing list