module Control.Monad.Par.Scheds.Direct (
Sched(..),
Par,
IVar(..), IVarContents(..),
runPar, runParIO,
new, get, put_, fork,
newFull, newFull_, put,
spawn, spawn_, spawnP,
spawn1_
) where
import Control.Applicative
import Control.Concurrent hiding (yield)
import Data.IORef (IORef,newIORef,readIORef,writeIORef,atomicModifyIORef)
import Text.Printf (printf, hPrintf)
import GHC.Conc (numCapabilities,yield)
import "mtl" Control.Monad.Cont as C
import qualified "mtl" Control.Monad.Reader as RD
import qualified System.Random.MWC as Random
import System.IO (stderr)
import System.IO.Unsafe (unsafePerformIO)
import System.Mem.StableName (makeStableName, hashStableName)
import qualified Control.Monad.Par.Class as PC
import qualified Control.Monad.Par.Unsafe as UN
import Control.Monad.Par.Scheds.DirectInternal
(Par(..), Sched(..), HotVar, SessionID, Session(Session),
newHotVar, readHotVar, modifyHotVar, modifyHotVar_, writeHotVarRaw)
#ifdef NEW_GENERIC
import qualified Control.Par.Class as PN
import qualified Control.Par.Class.Unsafe as PU
#endif
import Control.DeepSeq
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe (catMaybes)
import Data.Word (Word64)
import Data.Concurrent.Deque.Class (WSDeque)
#ifdef USE_CHASELEV
#warning "Note: using Chase-Lev lockfree workstealing deques..."
import Data.Concurrent.Deque.ChaseLev.DequeInstance
import Data.Concurrent.Deque.ChaseLev as R
#else
import Data.Concurrent.Deque.Reference.DequeInstance
import Data.Concurrent.Deque.Reference as R
#endif
import qualified Control.Exception as E
import Prelude hiding (null)
import qualified Prelude
#if __GLASGOW_HASKELL__ <= 700
import GHC.Conc (forkOnIO)
forkOn = forkOnIO
#endif
#define PARPUTS
#define FORKPARENT
#define IDLING_ON
#define WAKEIDLE
#ifdef DEBUG_DIRECT
#warning "DEBUG: Activating debugging for Direct.hs"
import Debug.Trace (trace)
import System.Environment (getEnvironment)
theEnv = unsafePerformIO $ getEnvironment
dbg = True
dbglvl = 1
#else
dbg = False
dbglvl = 0
#endif
dbg :: Bool
dbglvl :: Int
_PARPUTS :: Bool
#ifdef PARPUTS
_PARPUTS = True
#else
_PARPUTS = False
#endif
_FORKPARENT :: Bool
#ifdef FORKPARENT
_FORKPARENT = True
#else
#warning "FORKPARENT POLICY NOT USED; THIS IS GENERALLY WORSE"
_FORKPARENT = False
#endif
_IDLING_ON :: Bool
#ifdef IDLING_ON
_IDLING_ON = True
#else
_IDLING_ON = False
#endif
_WAIT_FOR_WORKERS :: Bool
#ifdef WAIT_FOR_WORKERS
_WAIT_FOR_WORKERS = True
#else
_WAIT_FOR_WORKERS = False
#endif
type ROnly = RD.ReaderT Sched IO
newtype IVar a = IVar (IORef (IVarContents a))
data IVarContents a = Full a | Empty | Blocked [a -> IO ()]
unsafeParIO :: IO a -> Par a
unsafeParIO iom = Par (lift$ lift iom)
io :: IO a -> Par a
io = unsafeParIO
globalWorkerPool :: IORef (M.Map ThreadId Sched)
globalWorkerPool = unsafePerformIO $ newIORef M.empty
amINested :: ThreadId -> IO (Maybe Sched)
registerWorker :: ThreadId -> Sched -> IO ()
unregisterWorker :: ThreadId -> IO ()
#ifdef NESTED_SCHEDS
amINested tid = do
wp <- readIORef globalWorkerPool
return (M.lookup tid wp)
registerWorker tid sched =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.insert tid sched mp, ())
unregisterWorker tid =
atomicModifyIORef globalWorkerPool $
\ mp -> (M.delete tid mp, ())
#else
amINested _ = return Nothing
registerWorker _ _ = return ()
unregisterWorker _tid = return ()
#endif
popWork :: Sched -> IO (Maybe (Par ()))
popWork Sched{ workpool, no } = do
mb <- R.tryPopL workpool
when dbg $ case mb of
Nothing -> return ()
Just _ -> do sn <- makeStableName mb
printf " [%d] -> POP work unit %d\n" no (hashStableName sn)
return mb
pushWork :: Sched -> Par () -> IO ()
pushWork Sched { workpool, idle, no, isMain } task = do
R.pushL workpool task
when dbg $ do sn <- makeStableName task
printf " [%d] -> PUSH work unit %d\n" no (hashStableName sn)
#if defined(IDLING_ON) && defined(WAKEIDLE)
tryWakeIdle idle
#endif
return ()
tryWakeIdle :: HotVar [MVar Bool] -> IO ()
tryWakeIdle idle = do
idles <- readHotVar idle
when (not (Prelude.null idles)) $ do
when dbg$ printf "Waking %d idle thread(s).\n" (length idles)
r <- modifyHotVar idle (\is -> case is of
[] -> ([], return ())
(i:ils) -> (ils, putMVar i False))
r
rand :: HotVar Random.GenIO -> IO Int
rand ref = Random.uniformR (0, numCapabilities1) =<< readHotVar ref
instance NFData (IVar a) where
rnf _ = ()
runPar = unsafePerformIO . runParIO
runNewSessionAndWait :: String -> Sched -> Par b -> IO b
runNewSessionAndWait name sched userComp = do
tid <- myThreadId
sid <- modifyHotVar (sessionCounter sched) (\ x -> (x+1,x))
_ <- modifyHotVar (activeSessions sched) (\ set -> (S.insert sid set, ()))
ref <- newIORef (error$ "Empty session-result ref ("++name++") should never be touched (sid "++ show sid++", "++show tid ++")")
newFlag <- newHotVar False
_ <- modifyHotVar (sessions sched) (\ ls -> ((Session sid newFlag) : ls, ()))
let userComp' = do when dbg$ io$ do
tid2 <- myThreadId
printf " [%d %s] Starting Par computation on %s.\n" (no sched) (show tid2) name
ans <- userComp
io$ do when (dbglvl>=1) $ do
tid3 <- myThreadId
printf " [%d %s] Continuation for %s called, finishing it up (%d)...\n" (no sched) (show tid3) name sid
writeIORef ref ans
writeHotVarRaw newFlag True
modifyHotVar (activeSessions sched) (\ set -> (S.delete sid set, ()))
kont :: Word64 -> a -> ROnly ()
kont n = trivialCont$ "("++name++", sid "++show sid++", round "++show n++")"
loop :: Word64 -> ROnly ()
loop n = do flg <- liftIO$ readIORef newFlag
unless flg $ do
when dbg $ liftIO$ do
tid4 <- myThreadId
printf " [%d %s] BOUNCE %d... going into reschedule until finished.\n" (no sched) (show tid4) n
rescheduleR 0 $ trivialCont$ "("++name++", sid "++show sid++")"
loop (n+1)
runReaderWith sched (C.runContT (unPar userComp') (kont 0))
runReaderWith sched (loop 1)
when (dbglvl>=1)$ do
active <- readHotVar (activeSessions sched)
sess@True <- readHotVar newFlag
printf " [%d %s] RETURN from %s (sessFin %s) runContT (%d) active set %s\n"
(no sched) (show tid) name (show sess) sid (show active)
modifyHotVar_ (sessions sched) $ \ (Session sid2 _ : tl) ->
if sid == sid2
then tl
else error$ "Tried to pop the session stack and found we ("++show sid
++") were not on the top! (instead "++show sid2++")"
readIORef ref
runParIO userComp = do
tid <- myThreadId
#if __GLASGOW_HASKELL__ >= 701 /* 20110301 */
(main_cpu, _) <- threadCapability tid
#else
let main_cpu = 0
#endif
maybSched <- amINested tid
tidorig <- myThreadId
case maybSched of
Just (sched) -> do
sid0 <- readHotVar (sessionCounter sched)
when (dbglvl>=1)$ printf " [%d %s] runPar called from existing worker thread, new session (%d)....\n" (no sched) (show tid) (sid0 + 1)
runNewSessionAndWait "nested runPar" sched userComp
Nothing -> do
allscheds <- makeScheds main_cpu
[Session _ topSessFlag] <- readHotVar$ sessions$ head allscheds
mfin <- newEmptyMVar
doneFlags <- forM (zip [0..] allscheds) $ \(cpu,sched) -> do
workerDone <- newEmptyMVar
let wname = ("(worker "++show cpu++" of originator "++show tidorig++")")
_ <- forkWithExceptions (forkOn cpu) wname $ do
tid2 <- myThreadId
registerWorker tid2 sched
if (cpu /= main_cpu)
then do when dbg$ printf " [%d %s] Anonymous worker entering scheduling loop.\n" cpu (show tid2)
runReaderWith sched $ rescheduleR 0 (trivialCont (wname++show tid2))
when dbg$ printf " [%d] Anonymous worker exited scheduling loop. FINISHED.\n" cpu
putMVar workerDone cpu
return ()
else do x <- runNewSessionAndWait "top-lvl main worker" sched userComp
writeIORef topSessFlag True
when dbg$ do printf " *** Out of entire runContT user computation on main thread %s.\n" (show tid2)
putMVar mfin x
unregisterWorker tid
return (if cpu == main_cpu then Nothing else Just workerDone)
when _WAIT_FOR_WORKERS $ do
when dbg$ printf " *** [%s] Originator thread: waiting for workers to complete." (show tidorig)
forM_ (catMaybes doneFlags) $ \ mv -> do
n <- readMVar mv
when dbg$ printf " * [%s] Worker %s completed\n" (show tidorig) (show n)
when dbg$ do printf " *** [%s] Reading final MVar on originator thread.\n" (show tidorig)
#ifdef DEBUG_DIRECT
busyTakeMVar (" The global wait "++ show tidorig) mfin
#else
takeMVar mfin
#endif
makeScheds :: Int -> IO [Sched]
makeScheds main = do
when dbg$ do tid <- myThreadId
printf "[initialization] Creating %d worker threads, currently on %s\n" numCapabilities (show tid)
workpools <- replicateM numCapabilities $ R.newQ
rngs <- replicateM numCapabilities $ Random.create >>= newHotVar
idle <- newHotVar []
sessionFinished <- newHotVar False
sessionStacks <- mapM newHotVar (replicate numCapabilities [Session baseSessionID sessionFinished])
activeSessions <- newHotVar S.empty
sessionCounter <- newHotVar (baseSessionID + 1)
let allscheds = [ Sched { no=x, idle, isMain= (x==main),
workpool=wp, scheds=allscheds, rng=rng,
sessions = stck,
activeSessions=activeSessions,
sessionCounter=sessionCounter
}
| x <- [0 .. numCapabilities1]
| wp <- workpools
| rng <- rngs
| stck <- sessionStacks
]
return allscheds
baseSessionID :: SessionID
baseSessionID = 1000
new :: Par (IVar a)
new = io$ do r <- newIORef Empty
return (IVar r)
get (IVar vr) = do
callCC $ \kont ->
do
e <- io$ readIORef vr
case e of
Full a -> return a
_ -> do
sch <- RD.ask
# ifdef DEBUG_DIRECT
sn <- io$ makeStableName vr
let resched = trace (" ["++ show (no sch) ++ "] - Rescheduling on unavailable ivar "++show (hashStableName sn)++"!")
#else
let resched =
# endif
longjmpSched
r <- io$ atomicModifyIORef vr $ \x -> case x of
Empty -> (Blocked [pushWork sch . kont], resched)
Full a -> (Full a, return a)
Blocked ks -> (Blocked (pushWork sch . kont:ks), resched)
r
unsafePeek :: IVar a -> Par (Maybe a)
unsafePeek (IVar v) = do
e <- io$ readIORef v
case e of
Full a -> return (Just a)
_ -> return Nothing
put_ (IVar vr) !content = do
sched <- RD.ask
ks <- io$ do
ks <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, [])
Full _ -> error "multiple put"
Blocked ks -> (Full content, ks)
#ifdef DEBUG_DIRECT
when (dbglvl >= 3) $ do
sn <- makeStableName vr
printf " [%d] Put value %s into IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length ks)
return ()
#endif
return ks
wakeUp sched ks content
unsafeTryPut (IVar vr) !content = do
sched <- RD.ask
(ks,res) <- io$ do
pr <- atomicModifyIORef vr $ \e -> case e of
Empty -> (Full content, ([], content))
Full x -> (Full x, ([], x))
Blocked ks -> (Full content, (ks, content))
#ifdef DEBUG_DIRECT
sn <- makeStableName vr
printf " [%d] unsafeTryPut: value %s in IVar %d. Waking up %d continuations.\n"
(no sched) (show content) (hashStableName sn) (length (fst pr))
#endif
return pr
wakeUp sched ks content
return res
wakeUp :: Sched -> [a -> IO ()]-> a -> Par ()
wakeUp _sched ks arg = loop ks
where
loop [] = return ()
loop (kont:rest) = do
if _PARPUTS then
do spawn_$ pMap kont rest
return ()
else
do io$ kont arg
loop rest
return ()
pMap kont [] = io$ kont arg
pMap kont (more:rest) =
do spawn_$ io$ kont arg
pMap more rest
fork :: Par () -> Par ()
fork task =
case _FORKPARENT of
True -> do
sched <- RD.ask
callCC$ \parent -> do
let wrapped = parent ()
io$ pushWork sched wrapped
task
longjmpSched
io$ printf " !!! ERROR: Should never reach this point #1\n"
when dbg$ do
sched2 <- RD.ask
io$ printf " - called parent continuation... was on worker [%d] now on worker [%d]\n" (no sched) (no sched2)
return ()
False -> do
sch <- RD.ask
when dbg$ io$ printf " [%d] forking task...\n" (no sch)
io$ pushWork sch task
longjmpSched :: Par a
longjmpSched = Par $ C.ContT (\ _k -> rescheduleR 0 (trivialCont "longjmpSched"))
rescheduleR :: Word64 -> (a -> ROnly ()) -> ROnly ()
rescheduleR cnt kont = do
mysched <- RD.ask
when dbg$ liftIO$ do tid <- myThreadId
sess <- readSessions mysched
null <- R.nullQ (workpool mysched)
printf " [%d %s] - Reschedule #%d... sessions %s, pool empty %s\n"
(no mysched) (show tid) cnt (show sess) (show null)
mtask <- liftIO$ popWork mysched
case mtask of
Nothing -> do
(Session _ finRef):_ <- liftIO$ readIORef $ sessions mysched
fin <- liftIO$ readIORef finRef
if fin
then do when (dbglvl >= 1) $ liftIO $ do
tid <- myThreadId
sess <- readSessions mysched
printf " [%d %s] - DROP out of reschedule loop, sessionFinished=%s, all sessions %s\n"
(no mysched) (show tid) (show fin) (show sess)
empt <- R.nullQ$ workpool mysched
when (not empt) $ do
printf " [%d %s] - WARNING - leaving rescheduleR while local workpoll is nonempty\n"
(no mysched) (show tid)
kont (error "Direct.hs: The result value from rescheduleR should not be used.")
else do
liftIO$ steal mysched
#ifdef WAKEIDLE
#endif
liftIO yield
rescheduleR (cnt+1) kont
Just task -> do
when dbg $ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] popped work %d from own queue\n" (no mysched) (hashStableName sn)
let C.ContT fn = unPar task
fn (\ _ -> do
sch <- RD.ask
when dbg$ liftIO$ printf " + task finished successfully on cpu %d, calling reschedule continuation..\n" (no sch)
rescheduleR 0 kont)
steal :: Sched -> IO ()
steal mysched@Sched{ idle, scheds, rng, no=my_no } = do
when (dbglvl>=2)$ do tid <- myThreadId
printf " [%d %s] + stealing\n" my_no (show tid)
i <- getnext (1 :: Int)
go maxtries i
where
maxtries = 20 * numCapabilities
getnext _ = rand rng
go 0 _ | _IDLING_ON =
do m <- newEmptyMVar
r <- modifyHotVar idle $ \is -> (m:is, is)
if length r == numCapabilities 1
then do
when dbg$ printf " [%d] | initiating shutdown\n" my_no
mapM_ (\vr -> putMVar vr True) r
else do
done <- takeMVar m
if done
then do
when dbg$ printf " [%d] | shutting down\n" my_no
return ()
else do
when dbg$ printf " [%d] | woken up\n" my_no
i <- getnext (1::Int)
go maxtries i
go 0 _i | _IDLING_ON == False = yield
go tries i
| i == my_no = do i' <- getnext i
go (tries1) i'
| otherwise = do
let schd = scheds!!i
when (dbglvl>=2)$ printf " [%d] | trying steal from %d\n" my_no (no schd)
let dq = workpool schd
r <- R.tryPopR dq
case r of
Just task -> do
when dbg$ do sn <- makeStableName task
printf " [%d] | stole work (unit %d) from cpu %d\n" my_no (hashStableName sn) (no schd)
runReaderWith mysched $
C.runContT (unPar task)
(\_ -> do
when dbg$ do sn <- liftIO$ makeStableName task
liftIO$ printf " [%d] | DONE running stolen work (unit %d) from %d\n" my_no (hashStableName sn) (no schd)
return ())
Nothing -> do i' <- getnext i
go (tries1) i'
errK :: t
errK = error "Error cont: this closure shouldn't be used"
trivialCont :: String -> a -> ROnly ()
trivialCont str _ = do
#ifdef DEBUG_DIRECT
liftIO$ printf " !! trivialCont evaluated, msg: %s\n" str
#endif
return ()
spawn1_ f x =
#ifdef DEBUG_DIRECT
do sn <- io$ makeStableName f
sch <- RD.ask; when dbg$ io$ printf " [%d] spawning fn %d with arg %s\n" (no sch) (hashStableName sn) (show x)
#endif
spawn_ (f x)
newFull_ a = do v <- new
put_ v a
return v
newFull a = deepseq a (newFull_ a)
put v a = deepseq a (put_ v a)
spawn p = do r <- new; fork (p >>= put r); return r
spawn_ p = do r <- new; fork (p >>= put_ r); return r
spawnP a = spawn (return a)
#ifdef DEBUG_DIRECT
put :: (Show a, NFData a) => IVar a -> a -> Par ()
spawn :: (Show a, NFData a) => Par a -> Par (IVar a)
spawn_ :: Show a => Par a -> Par (IVar a)
spawn1_ :: (Show a, Show b) => (a -> Par b) -> a -> Par (IVar b)
spawnP :: (Show a, NFData a) => a -> Par (IVar a)
put_ :: Show a => IVar a -> a -> Par ()
get :: Show a => IVar a -> Par a
runPar :: Show a => Par a -> a
runParIO :: Show a => Par a -> IO a
newFull :: (Show a, NFData a) => a -> Par (IVar a)
newFull_ :: Show a => a -> Par (IVar a)
unsafeTryPut :: Show b => IVar b -> b -> Par b
#else
spawn :: NFData a => Par a -> Par (IVar a)
spawn_ :: Par a -> Par (IVar a)
spawn1_ :: (a -> Par b) -> a -> Par (IVar b)
spawnP :: NFData a => a -> Par (IVar a)
put_ :: IVar a -> a -> Par ()
put :: NFData a => IVar a -> a -> Par ()
get :: IVar a -> Par a
runPar :: Par a -> a
runParIO :: Par a -> IO a
newFull :: NFData a => a -> Par (IVar a)
newFull_ :: a -> Par (IVar a)
unsafeTryPut :: IVar b -> b -> Par b
instance PC.ParFuture IVar Par where
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PC.ParIVar IVar Par where
fork = fork
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
instance UN.ParUnsafe IVar Par where
unsafePeek = unsafePeek
unsafeTryPut = unsafeTryPut
unsafeParIO = unsafeParIO
#endif
#ifdef NEW_GENERIC
instance PU.ParMonad Par where
fork = fork
internalLiftIO io = Par (lift $ lift io)
instance PU.ParThreadSafe Par where
unsafeParIO io = Par (lift $ lift io)
instance PN.ParFuture Par where
type Future Par = IVar
type FutContents Par a = ()
get = get
spawn = spawn
spawn_ = spawn_
spawnP = spawnP
instance PN.ParIVar Par where
new = new
put_ = put_
newFull = newFull
newFull_ = newFull_
#endif
runReaderWith :: r -> RD.ReaderT r m a -> m a
runReaderWith state m = RD.runReaderT m state
sanityCheck :: [Sched] -> IO ()
sanityCheck allscheds = do
forM_ allscheds $ \ Sched{no, workpool} -> do
b <- R.nullQ workpool
when (not b) $ do
() <- printf "WARNING: After main thread exited non-empty queue remains for worker %d\n" no
return ()
printf "Sanity check complete.\n"
dbgTakeMVar :: String -> MVar a -> IO a
dbgTakeMVar msg mv =
E.catch (takeMVar mv) (\(_::IOError) -> doDebugStuff)
where
doDebugStuff = do printf "This takeMVar blocked indefinitely!: %s\n" msg
error "failed"
forkIO_Suppress :: Int -> IO () -> IO ThreadId
forkIO_Suppress whre action =
forkOn whre $
E.handle (\e ->
case (e :: E.BlockedIndefinitelyOnMVar) of
_ -> do
putStrLn$"CAUGHT child thread exception: "++show e
return ()
)
action
forkWithExceptions :: (IO () -> IO ThreadId) -> String -> IO () -> IO ThreadId
forkWithExceptions forkit descr action = do
parent <- myThreadId
forkit $ do
tid <- myThreadId
E.catch action
(\ e ->
case E.fromException e of
Just E.ThreadKilled -> printf
"\nThreadKilled exception inside child thread, %s (not propagating!): %s\n" (show tid) (show descr)
_ -> do printf
"\nException inside child thread %s, %s: %s\n" (show descr) (show tid) (show e)
E.throwTo parent (e :: E.SomeException)
)
readSessions :: Sched -> IO [(SessionID, Bool)]
readSessions sched = do
ls <- readIORef (sessions sched)
bools <- mapM (\ (Session _ r) -> readIORef r) ls
return (zip (map (\ (Session sid _) -> sid) ls) bools)