[Haskell-cafe] One-shot? (was: Global variables and stuff)

Keean Schupke k.schupke at imperial.ac.uk
Wed Nov 10 14:27:42 EST 2004


Adrian Hey wrote:

>Suppose I had..
>
>myOtherRef :: IO (IORef Char)
>myOtherRef = once (newIORef 'a')
>
>There's nothing to stop the compiler doing CSE and producing, in effect..
>
>commonRef :: IO (IORef Char)
>commonRef = once (newIORef 'a')
>
>.. followed by substitution of all occurrences of myRef and myOtherRef
>with commonRef. I think this would break your programs.
>  
>
Well thats certainly not the case with the solution I posted. There are
no unsafe operations at all (Well the FFI imports are marked 'unsafe'
but that means it is unsafe for them to call back into Haskell)...

The solution I posted uses no unsafePerformIO, and the type of action
allowed is limited to "IO ()". In other word all results must be returned
as side effects, and the computation either happens (if its the first time)
or doesn't happen...

Also the semaphore method is very flexible, you can run things exactly 
twice,
or you can reset the semaphore and allow the next init to happen (sort of
closing the library and opening it again)... Also once-ness can be 
restricted
accross many domais, thread, process, process-group, multiple sequential
executions, once and for all (may only run once on any machine)... Of course
in this case it ties up one semaphore indefiniely - but hey its a single 
bit, and
there are 65536x32 semaphores available, so its not really going to cause
a problem.

Posix(1b) semaphores with string names would be even better (and have a
slightly neater interface) but linux does not seem to support sem_open, so
I have had to use SYSV semaphores.

    Keean.


More information about the Haskell-Cafe mailing list