Talk:Parallelism vs. Concurrency
Parallelism vs concurrency: what's the difference?
Visible side effects.
- Have a look at this
ugly eysore"prototype definition" of
par :: a -> b -> b par x y = case unsafeLocalState (forkIO (evalIO x >> return ())) of !_ -> y
evalIO :: a -> IO a forkIO :: IO () -> IO ThreadId
xis well-defined (it contains no
xis well-behaved (not throwing exceptions or causing errors);
ThreadIdto its argument, adds it to the work-queue and returns the identifier;
- Some time later,
forkIO's argument is called, causing
evalIOto start evaluating
yis still being evaluated when the evaluation of
xcommences, then we have elementary parallelism: concurrency, but with no visible side-effects.
- Now have a look at this
nearly-as-uglyprototype definition for
forkIO :: IO () -> IO ThreadId forkIO act = do t <- unsafeInterleaveIO act case par t () of !_ -> do i' <- itsThreadId t case i' of Just i -> return i Nothing -> ioError "forkIO"
itsThreadId :: a -> IO (Maybe ThreadId)
Nothingif it's argument had not been previously used by
par t ()causes a new
ThreadIdto be attached to
tby the implementation;
i', the (possible) identifier for
forkIOthen extracts and returns the identifier.
This looks very much like elementary concurrency: parallelism, but having visible side effects.
Can either of these prototypes ever go mainstream?
- As shown by it's type signature,
paris supposed to be pure: avoiding the use of
unsafeLocalStatemeans making it primitive;
- While the use of
unsafeInterleaveIOmay annoy some, it being one of the earlier Haskell extensions means it's widely available.
For now, using a primitive
par (and others) to define
forkIO looks like the simplest option...but if using
unsafeInterleaveIO really does annoy you, how about this:
forkIO :: (OI -> ()) -> OI -> ThreadId forkIO act u = let !(u1:u2:u3:_) = parts u in let t = act u1 in case par t () of !_ -> case itsThreadId t u2 of Just i -> i Nothing -> ioError "forkIO" u3
-- Atravers Tue Apr 20 06:04:10 UTC 2021