[Haskell-cafe] Using unsafePerformIO
Adrian Hey
ahey at iee.org
Sat Jul 30 04:43:58 EDT 2005
On Friday 29 Jul 2005 4:01 pm, Dinh Tien Tuan Anh wrote:
> Hi, i have the following
>
> f :: [a] -> IO a
> f xs = do
> m <- newMVar
> c1 <- forkIO f1 xs m
> c2 <- forkIO f2 xs m
> c3 <- forkIO f3 xs m
> c<- takeMVar m
> killThread c1
> killThread c2
> killThread c3
> return c
>
>
>
> co (x:xs)
> c == 1 = 1: co xs
> otherwise = (-1): co xs
> where c = unsafePerformIO (f (x:xs))
>
>
>
>
> is it safe to use unsafePerformIO that way ? Please tell me why if it is
> not.
It depends on whether or not f behaves like a function.
AFAICS it is safe provided..
f always returns the same value for a given argument list
and..
f has no observable side effects.
It looks to me like what you're trying to do is run three parallel
evaluation algorithms and take the answer from whichever one
delivers an answer first (via the MVar, which should be empty
initially). So as long as..
f1,f2,f3 all deliver the same answer (if they deliver an answer at all)
and
that answer depends on nothing but xs
and
none of them have any observable side effects
then
I guess you're probably safe.
Regards
--
Adrian Hey
More information about the Haskell-Cafe
mailing list