vis
vis

Reputation: 2279

Why MVar does not work with `par`?

Just curious. If I have 2 threads spawn using forkIO, communication between them can be done using MVar. I wonder if the same apply when using parallel Haskell's spark created using par. I understand par does not create an actual thread but just a pointer to some computation that can happen in parallel.

The following code compiles, main raises the following error: thread blocked indefinitely in an MVar operation.

t1 a = putMVar a "Hi"
t2 a = do
  v <- takeMVar a
  print v

main1 = do
  a <- newEmptyMVar
  forkIO (t1 a)
  forkIO (t2 a)

main = do
  a <- newEmptyMVar
  (t1 a) `par` (t2 a)   

Upvotes: 2

Views: 196

Answers (2)

Alfonso Vill&#233;n
Alfonso Vill&#233;n

Reputation: 373

As far as I know, a thread should run takeMVar first, then putMVar. That way, a thread blocks access to the MVar by the other threads.

Upvotes: 0

Don Stewart
Don Stewart

Reputation: 137937

I wonder if the same apply when using parallel Haskell's spark created using par

No, this is not really possible. The MVar is an explicit, non-deterministic communication mechanism for use when manually controlling threads. par sparks are a much higher level abstraction, where the GHC runtime takes care of the communication for you.

When you attempt to spark an IO action, nothing happens, as sparked actions can be pure computations only.

Upvotes: 7

Related Questions