Quantcast

Re: Haskell-Cafe Digest, Vol 33, Issue 9

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Haskell-Cafe Digest, Vol 33, Issue 9

Alberto G. Corona
Hi,
I´m trying to make a searchable transactional cache using STM. The
whole idea is to use indexed TVar variables using a FiniteMap. another
TVar holds the finitemap . This last TVar has to be a global variable.
I found that when handled as global, a TVar does not keep the state.
For example:


stmcache= newTVar 0

main= do
        v<- val
        v<- val
        print v


val = atomically $! do
                               cache <- stmcache
                x <- readTVar  cache
                writeTVar cache (x+1)
                return x

this code print 0 instead of 1 as the result of incrementing cache and
retrieving it the second time



The same happens with:



iocache= atomically $ newTVar 0 `debug` "newTVar"

main= do
       v<- val
       v<- val
       print v
       getChar

val = do
        cache<- iocache
        atomically $! do
             x <- readTVar cache
             writeTVar cache (x+1)
        return x



here i used a IO TVar  global instead of a  STM TVar

This other version , that passes TVar as parameter, does work:

iocache= atomically $ newTVar 0 `debug` "newTVar"



main= do
       cache<-iocache
       v<- val cache
       v<- val cache
       print v


val cache=
       atomically $! do
       x <- readTVar cache
       writeTVar cache (x+1)


I need the global version since the cache acces may be in any location
on the program....

Anyone know a solution using STM? The MVar version works OK, but
blocking the entire index is not the best solution....
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Re: Haskell-Cafe Digest, Vol 33, Issue 9

Albert Y. C. Lai
"Alberto G. Corona " <[hidden email]> writes:

> stmcache= newTVar 0

I will explain what this doesn't with an analogy.

import Data.IORef

notglobal = newIORef True

main = do a <- notglobal
          b <- notglobal
          writeIORef a False
          x <- readIORef b
          print x

To better show what's going on, I also provide this for contrast:

import Data.IORef
import System.IO.Unsafe

global = unsafePerformIO (newIORef True)

main = do x <- readIORef global
          print x
          writeIORef global False
          x <- readIORef global
          print x
_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Loading...