Movatterモバイル変換


[0]ホーム

URL:


{-# LANGUAGE Trustworthy #-}{-# LANGUAGE CPP           , MagicHash           , UnboxedTuples           , ScopedTypeVariables           , RankNTypes  #-}{-# OPTIONS_GHC -Wno-deprecations #-}-- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN-- and Control.Concurrent.SampleVar imports.------------------------------------------------------------------------------- |-- Module      :  Control.Concurrent-- Copyright   :  (c) The University of Glasgow 2001-- License     :  BSD-style (see the file libraries/base/LICENSE)---- Maintainer  :  libraries@haskell.org-- Stability   :  experimental-- Portability :  non-portable (concurrency)---- A common interface to a collection of useful concurrency-- abstractions.-------------------------------------------------------------------------------moduleControl.Concurrent(-- * Concurrent Haskell-- $conc_intro-- * Basic concurrency operationsThreadId,myThreadId,forkIO,forkFinally,forkIOWithUnmask,killThread,throwTo,-- ** Threads with affinityforkOn,forkOnWithUnmask,getNumCapabilities,setNumCapabilities,threadCapability,-- * Scheduling-- $conc_schedulingyield,-- ** Blocking-- $blocking-- ** WaitingthreadDelay,threadWaitRead,threadWaitWrite,threadWaitReadSTM,threadWaitWriteSTM,-- * Communication abstractionsmoduleControl.Concurrent.MVar,moduleControl.Concurrent.Chan,moduleControl.Concurrent.QSem,moduleControl.Concurrent.QSemN,-- * Bound Threads-- $boundthreadsrtsSupportsBoundThreads,forkOS,forkOSWithUnmask,isCurrentThreadBound,runInBoundThread,runInUnboundThread,-- * Weak references to ThreadIdsmkWeakThreadId,-- * GHC's implementation of concurrency-- |This section describes features specific to GHC's-- implementation of Concurrent Haskell.-- ** Haskell threads and Operating System threads-- $osthreads-- ** Terminating the program-- $termination-- ** Pre-emption-- $preemption-- ** Deadlock-- $deadlock)whereimportControl.Exception.BaseasExceptionimportGHC.Conchiding(threadWaitRead,threadWaitWrite,threadWaitReadSTM,threadWaitWriteSTM)importGHC.IO(unsafeUnmask,catchException)importGHC.IORef(newIORef,readIORef,writeIORef)importGHC.BaseimportSystem.Posix.Types(Fd)importForeign.StablePtrimportForeign.C.Types#if defined(mingw32_HOST_OS)importForeign.CimportSystem.IOimportData.Functor(void)importData.Int(Int64)#elseimportqualifiedGHC.Conc#endifimportControl.Concurrent.MVarimportControl.Concurrent.ChanimportControl.Concurrent.QSemimportControl.Concurrent.QSemN{- $conc_introThe concurrency extension for Haskell is described in the paper/Concurrent Haskell/<http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.Concurrency is \"lightweight\", which means that both thread creationand context switching overheads are extremely low.  Scheduling ofHaskell threads is done internally in the Haskell runtime system, anddoesn't make use of any operating system-supplied thread packages.However, if you want to interact with a foreign library that expects yourprogram to use the operating system-supplied thread package, you can do soby using 'forkOS' instead of 'forkIO'.Haskell threads can communicate via 'MVar's, a kind of synchronisedmutable variable (see "Control.Concurrent.MVar").  Several commonconcurrency abstractions can be built from 'MVar's, and these areprovided by the "Control.Concurrent" library.In GHC, threads may also communicate via exceptions.-}{- $conc_scheduling    Scheduling may be either pre-emptive or co-operative,    depending on the implementation of Concurrent Haskell (see below    for information related to specific compilers).  In a co-operative    system, context switches only occur when you use one of the    primitives defined in this module.  This means that programs such    as:>   main = forkIO (write 'a') >> write 'b'>     where write c = putChar c >> write c    will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,    instead of some random interleaving of @a@s and @b@s.  In    practice, cooperative multitasking is sufficient for writing    simple graphical user interfaces.-}{- $blockingDifferent Haskell implementations have different characteristics withregard to which operations block /all/ threads.Using GHC without the @-threaded@ option, all foreign calls will blockall other Haskell threads in the system, although I\/O operations willnot.  With the @-threaded@ option, only foreign calls with the @unsafe@attribute will block all other threads.-}-- | Fork a thread and call the supplied function when the thread is about-- to terminate, with an exception or a returned value.  The function is-- called with asynchronous exceptions masked.---- > forkFinally action and_then =-- >   mask $ \restore ->-- >     forkIO $ try (restore action) >>= and_then---- This function is useful for informing the parent when a child-- terminates, for example.---- @since 4.6.0.0forkFinally::IOa->(EitherSomeExceptiona->IO())->IOThreadIdforkFinallyactionand_then=mask$\restore->forkIO$try(restoreaction)>>=and_then-- ----------------------------------------------------------------------------- Bound Threads{- $boundthreads   #boundthreads#Support for multiple operating system threads and bound threads as describedbelow is currently only available in the GHC runtime system if you use the/-threaded/ option when linking.Other Haskell systems do not currently support multiple operating system threads.A bound thread is a haskell thread that is /bound/ to an operating systemthread. While the bound thread is still scheduled by the Haskell run-timesystem, the operating system thread takes care of all the foreign calls madeby the bound thread.To a foreign library, the bound thread will look exactly like an ordinaryoperating system thread created using OS functions like @pthread_create@or @CreateThread@.Bound threads can be created using the 'forkOS' function below. All foreignexported functions are run in a bound thread (bound to the OS thread thatcalled the function). Also, the @main@ action of every Haskell program isrun in a bound thread.Why do we need this? Because if a foreign library is called from a threadcreated using 'forkIO', it won't have access to any /thread-local state/ -state variables that have specific values for each OS thread(see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, somelibraries (OpenGL, for example) will not work from a thread created using'forkIO'. They work fine in threads created using 'forkOS' or when calledfrom @main@ or from a @foreign export@.In terms of performance, 'forkOS' (aka bound) threads are much moreexpensive than 'forkIO' (aka unbound) threads, because a 'forkOS'thread is tied to a particular OS thread, whereas a 'forkIO' threadcan be run by any OS thread.  Context-switching between a 'forkOS'thread and a 'forkIO' thread is many times more expensive than betweentwo 'forkIO' threads.Note in particular that the main program thread (the thread running@Main.main@) is always a bound thread, so for good concurrencyperformance you should ensure that the main thread is not doingrepeated communication with other threads in the system.  Typicallythis means forking subthreads to do the work using 'forkIO', andwaiting for the results in the main thread.-}-- | 'True' if bound threads are supported.-- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'-- will always return 'False' and both 'forkOS' and 'runInBoundThread' will-- fail.foreignimportccallunsafertsSupportsBoundThreads::Bool{- |Like 'forkIO', this sparks off a new thread to run the 'IO'computation passed as the first argument, and returns the 'ThreadId'of the newly created thread.However, 'forkOS' creates a /bound/ thread, which is necessary if youneed to call foreign (non-Haskell) libraries that make use ofthread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").Using 'forkOS' instead of 'forkIO' makes no difference at all to thescheduling behaviour of the Haskell runtime system.  It is a commonmisconception that you need to use 'forkOS' instead of 'forkIO' toavoid blocking all the Haskell threads when making a foreign call;this isn't the case.  To allow foreign calls to be made withoutblocking all the Haskell threads (with GHC), it is only necessary touse the @-threaded@ option when linking your program, and to make surethe foreign import is not marked @unsafe@.-}forkOS::IO()->IOThreadIdforeignexportccallforkOS_entry::StablePtr(IO())->IO()foreignimportccall"forkOS_entry"forkOS_entry_reimported::StablePtr(IO())->IO()forkOS_entry::StablePtr(IO())->IO()forkOS_entrystableAction=doaction<-deRefStablePtrstableActionactionforeignimportccallforkOS_createThread::StablePtr(IO())->IOCIntfailNonThreaded::IOafailNonThreaded=fail$"RTS doesn't support multiple OS threads "++"(use ghc -threaded when linking)"forkOSaction0|rtsSupportsBoundThreads=domv<-newEmptyMVarb<-Exception.getMaskingStatelet-- async exceptions are masked in the child if they are masked-- in the parent, as for forkIO (see #1048). forkOS_createThread-- creates a thread with exceptions masked by default.action1=casebofUnmasked->unsafeUnmaskaction0MaskedInterruptible->action0MaskedUninterruptible->uninterruptibleMask_action0action_plus=catchaction1childHandlerentry<-newStablePtr(myThreadId>>=putMVarmv>>action_plus)err<-forkOS_createThreadentrywhen(err/=0)$fail"Cannot create OS thread."tid<-takeMVarmvfreeStablePtrentryreturntid|otherwise=failNonThreaded-- | Like 'forkIOWithUnmask', but the child thread is a bound thread,-- as with 'forkOS'.forkOSWithUnmask::((foralla.IOa->IOa)->IO())->IOThreadIdforkOSWithUnmaskio=forkOS(iounsafeUnmask)-- | Returns 'True' if the calling thread is /bound/, that is, if it is-- safe to use foreign libraries that rely on thread-local state from the-- calling thread.isCurrentThreadBound::IOBoolisCurrentThreadBound=IO$\s#->caseisCurrentThreadBound#s#of(#s2#,flg#)->(#s2#,isTrue#(flg/=#0#)#){- |Run the 'IO' computation passed as the first argument. If the calling threadis not /bound/, a bound thread is created temporarily. @runInBoundThread@doesn't finish until the 'IO' computation finishes.You can wrap a series of foreign function calls that rely on thread-local statewith @runInBoundThread@ so that you can use them without knowing whether thecurrent thread is /bound/.-}runInBoundThread::IOa->IOarunInBoundThreadaction|rtsSupportsBoundThreads=dobound<-isCurrentThreadBoundifboundthenactionelsedoref<-newIORefundefinedletaction_plus=Exception.tryaction>>=writeIORefrefbracket(newStablePtraction_plus)freeStablePtr(\cEntry->forkOS_entry_reimportedcEntry>>readIORefref)>>=unsafeResult|otherwise=failNonThreaded{- |Run the 'IO' computation passed as the first argument. If the calling threadis /bound/, an unbound thread is created temporarily using 'forkIO'.@runInBoundThread@ doesn't finish until the 'IO' computation finishes.Use this function /only/ in the rare case that you have actually observed aperformance loss due to the use of bound threads. A program thatdoesn't need its main thread to be bound and makes /heavy/ use of concurrency(e.g. a web server), might want to wrap its @main@ action in@runInUnboundThread@.Note that exceptions which are thrown to the current thread are thrown in turnto the thread that is executing the given computation. This ensures there'salways a way of killing the forked thread.-}runInUnboundThread::IOa->IOarunInUnboundThreadaction=dobound<-isCurrentThreadBoundifboundthendomv<-newEmptyMVarmask$\restore->dotid<-forkIO$Exception.try(restoreaction)>>=putMVarmvletwait=takeMVarmv`catchException`\(e::SomeException)->Exception.throwTotide>>waitwait>>=unsafeResultelseactionunsafeResult::EitherSomeExceptiona->IOaunsafeResult=eitherException.throwIOreturn-- ----------------------------------------------------------------------------- threadWaitRead/threadWaitWrite-- | Block the current thread until data is available to read on the-- given file descriptor (GHC only).---- This will throw an 'IOError' if the file descriptor was closed-- while this thread was blocked.  To safely close a file descriptor-- that has been used with 'threadWaitRead', use-- 'GHC.Conc.closeFdWith'.threadWaitRead::Fd->IO()threadWaitReadfd#if defined(mingw32_HOST_OS)-- we have no IO manager implementing threadWaitRead on Windows.-- fdReady does the right thing, but we have to call it in a-- separate thread, otherwise threadWaitRead won't be interruptible,-- and this only works with -threaded.|threaded=withThread(waitFdfdFalse)|otherwise=casefdof0->do_<-hWaitForInputstdin(-1)return()-- hWaitForInput does work properly, but we can only-- do this for stdin since we know its FD._->errorWithoutStackTrace"threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"#else=GHC.Conc.threadWaitReadfd#endif-- | Block the current thread until data can be written to the-- given file descriptor (GHC only).---- This will throw an 'IOError' if the file descriptor was closed-- while this thread was blocked.  To safely close a file descriptor-- that has been used with 'threadWaitWrite', use-- 'GHC.Conc.closeFdWith'.threadWaitWrite::Fd->IO()threadWaitWritefd#if defined(mingw32_HOST_OS)|threaded=withThread(waitFdfdTrue)|otherwise=errorWithoutStackTrace"threadWaitWrite requires -threaded on Windows"#else=GHC.Conc.threadWaitWritefd#endif-- | Returns an STM action that can be used to wait for data-- to read from a file descriptor. The second returned value-- is an IO action that can be used to deregister interest-- in the file descriptor.---- @since 4.7.0.0threadWaitReadSTM::Fd->IO(STM(),IO())threadWaitReadSTMfd#if defined(mingw32_HOST_OS)|threaded=dov<-newTVarIONothingmask_$void$forkIO$doresult<-try(waitFdfdFalse)atomically(writeTVarv$Justresult)letwaitAction=doresult<-readTVarvcaseresultofNothing->retryJust(Right())->return()Just(Lefte)->throwSTM(e::IOException)letkillAction=return()return(waitAction,killAction)|otherwise=errorWithoutStackTrace"threadWaitReadSTM requires -threaded on Windows"#else=GHC.Conc.threadWaitReadSTMfd#endif-- | Returns an STM action that can be used to wait until data-- can be written to a file descriptor. The second returned value-- is an IO action that can be used to deregister interest-- in the file descriptor.---- @since 4.7.0.0threadWaitWriteSTM::Fd->IO(STM(),IO())threadWaitWriteSTMfd#if defined(mingw32_HOST_OS)|threaded=dov<-newTVarIONothingmask_$void$forkIO$doresult<-try(waitFdfdTrue)atomically(writeTVarv$Justresult)letwaitAction=doresult<-readTVarvcaseresultofNothing->retryJust(Right())->return()Just(Lefte)->throwSTM(e::IOException)letkillAction=return()return(waitAction,killAction)|otherwise=errorWithoutStackTrace"threadWaitWriteSTM requires -threaded on Windows"#else=GHC.Conc.threadWaitWriteSTMfd#endif#if defined(mingw32_HOST_OS)foreignimportccallunsafe"rtsSupportsBoundThreads"threaded::BoolwithThread::IOa->IOawithThreadio=dom<-newEmptyMVar_<-mask_$forkIO$tryio>>=putMVarmx<-takeMVarmcasexofRighta->returnaLefte->throwIO(e::IOException)waitFd::Fd->Bool->IO()waitFdfdwrite=dothrowErrnoIfMinus1_"fdReady"$fdReady(fromIntegralfd)(ifwritethen1else0)(-1)0foreignimportccallsafe"fdReady"fdReady::CInt->CBool->Int64->CBool->IOCInt#endif-- ----------------------------------------------------------------------------- More docs{- $osthreads      #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and      are managed entirely by the GHC runtime.  Typically Haskell      threads are an order of magnitude or two more efficient (in      terms of both time and space) than operating system threads.      The downside of having lightweight threads is that only one can      run at a time, so if one thread blocks in a foreign call, for      example, the other threads cannot continue.  The GHC runtime      works around this by making use of full OS threads where      necessary.  When the program is built with the @-threaded@      option (to link against the multithreaded version of the      runtime), a thread making a @safe@ foreign call will not block      the other threads in the system; another OS thread will take      over running Haskell threads until the original call returns.      The runtime maintains a pool of these /worker/ threads so that      multiple Haskell threads can be involved in external calls      simultaneously.      The "System.IO" library manages multiplexing in its own way.  On      Windows systems it uses @safe@ foreign calls to ensure that      threads doing I\/O operations don't block the whole runtime,      whereas on Unix systems all the currently blocked I\/O requests      are managed by a single thread (the /IO manager thread/) using      a mechanism such as @epoll@ or @kqueue@, depending on what is      provided by the host operating system.      The runtime will run a Haskell thread using any of the available      worker OS threads.  If you need control over which particular OS      thread is used to run a given Haskell thread, perhaps because      you need to call a foreign library that uses OS-thread-local      state, then you need bound threads (see "Control.Concurrent#boundthreads").      If you don't use the @-threaded@ option, then the runtime does      not make use of multiple OS threads.  Foreign calls will block      all other running Haskell threads until the call returns.  The      "System.IO" library still does multiplexing, so there can be multiple      threads doing I\/O, and this is handled internally by the runtime using      @select@.-}{- $termination      In a standalone GHC program, only the main thread is      required to terminate in order for the process to terminate.      Thus all other forked threads will simply terminate at the same      time as the main thread (the terminology for this kind of      behaviour is \"daemonic threads\").      If you want the program to wait for child threads to      finish before exiting, you need to program this yourself.  A      simple mechanism is to have each child thread write to an      'MVar' when it completes, and have the main      thread wait on all the 'MVar's before      exiting:>   myForkIO :: IO () -> IO (MVar ())>   myForkIO io = do>     mvar <- newEmptyMVar>     forkFinally io (\_ -> putMVar mvar ())>     return mvar      Note that we use 'forkFinally' to make sure that the      'MVar' is written to even if the thread dies or      is killed for some reason.      A better method is to keep a global list of all child      threads which we should wait for at the end of the program:>    children :: MVar [MVar ()]>    children = unsafePerformIO (newMVar [])>>    waitForChildren :: IO ()>    waitForChildren = do>      cs <- takeMVar children>      case cs of>        []   -> return ()>        m:ms -> do>           putMVar children ms>           takeMVar m>           waitForChildren>>    forkChild :: IO () -> IO ThreadId>    forkChild io = do>        mvar <- newEmptyMVar>        childs <- takeMVar children>        putMVar children (mvar:childs)>        forkFinally io (\_ -> putMVar mvar ())>>     main =>       later waitForChildren $>       ...      The main thread principle also applies to calls to Haskell from      outside, using @foreign export@.  When the @foreign export@ed      function is invoked, it starts a new main thread, and it returns      when this main thread terminates.  If the call causes new      threads to be forked, they may remain in the system after the      @foreign export@ed function has returned.-}{- $preemption      GHC implements pre-emptive multitasking: the execution of      threads are interleaved in a random fashion.  More specifically,      a thread may be pre-empted whenever it allocates some memory,      which unfortunately means that tight loops which do no      allocation tend to lock out other threads (this only seems to      happen with pathological benchmark-style code, however).      The rescheduling timer runs on a 20ms granularity by      default, but this may be altered using the      @-i\<n\>@ RTS option.  After a rescheduling      \"tick\" the running thread is pre-empted as soon as      possible.      One final note: the      @aaaa@ @bbbb@ example may not      work too well on GHC (see Scheduling, above), due      to the locking on a 'System.IO.Handle'.  Only one thread      may hold the lock on a 'System.IO.Handle' at any one      time, so if a reschedule happens while a thread is holding the      lock, the other thread won't be able to run.  The upshot is that      the switch from @aaaa@ to      @bbbbb@ happens infrequently.  It can be      improved by lowering the reschedule tick period.  We also have a      patch that causes a reschedule whenever a thread waiting on a      lock is woken up, but haven't found it to be useful for anything      other than this example :-)-}{- $deadlockGHC attempts to detect when threads are deadlocked using the garbagecollector.  A thread that is not reachable (cannot be found byfollowing pointers from live objects) must be deadlocked, and in thiscase the thread is sent an exception.  The exception is either'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM','NonTermination', or 'Deadlock', depending on the way in which thethread is deadlocked.Note that this feature is intended for debugging, and should not berelied on for the correct operation of your program.  There is noguarantee that the garbage collector will be accurate enough to detectyour deadlock, and no guarantee that the garbage collector will run ina timely enough manner.  Basically, the same caveats as for finalizersapply to deadlock detection.There is a subtle interaction between deadlock detection andfinalizers (as created by 'Foreign.Concurrent.newForeignPtr' or thefunctions in "System.Mem.Weak"): if a thread is blocked waiting for afinalizer to run, then the thread will be considered deadlocked andsent an exception.  So preferably don't do this, but if you have noalternative then it is possible to prevent the thread from beingconsidered deadlocked by making a 'StablePtr' pointing to it.  Don'tforget to release the 'StablePtr' later with 'freeStablePtr'.-}

[8]ページ先頭

©2009-2025 Movatter.jp