Movatterモバイル変換


[0]ホーム

URL:


{-# LANGUAGE Unsafe #-}{-# LANGUAGE CPP           , NoImplicitPrelude           , BangPatterns           , MagicHash           , UnboxedTuples           , UnliftedFFITypes           , StandaloneDeriving           , RankNTypes  #-}{-# OPTIONS_GHC -Wno-missing-signatures #-}{-# OPTIONS_HADDOCK not-home #-}------------------------------------------------------------------------------- |-- Module      :  GHC.Conc.Sync-- Copyright   :  (c) The University of Glasgow, 1994-2002-- License     :  see libraries/base/LICENSE---- Maintainer  :  cvs-ghc@haskell.org-- Stability   :  internal-- Portability :  non-portable (GHC extensions)---- Basic concurrency stuff.--------------------------------------------------------------------------------- No: #hide, because bits of this module are exposed by the stm package.-- However, we don't want this module to be the home location for the-- bits it exports, we'd rather have Control.Concurrent and the other-- higher level modules be the home.  Hence:-- #not-homemoduleGHC.Conc.Sync(ThreadId(..)-- * Forking and suchlike,forkIO,forkIOWithUnmask,forkOn,forkOnWithUnmask,numCapabilities,getNumCapabilities,setNumCapabilities,getNumProcessors,numSparks,childHandler,myThreadId,killThread,throwTo,par,pseq,runSparks,yield,labelThread,mkWeakThreadId,ThreadStatus(..),BlockReason(..),threadStatus,threadCapability,newStablePtrPrimMVar,PrimMVar-- * Allocation counter and quota,setAllocationCounter,getAllocationCounter,enableAllocationLimit,disableAllocationLimit-- * TVars,STM(..),atomically,retry,orElse,throwSTM,catchSTM,TVar(..),newTVar,newTVarIO,readTVar,readTVarIO,writeTVar,unsafeIOToSTM-- * Miscellaneous,withMVar,modifyMVar_,setUncaughtExceptionHandler,getUncaughtExceptionHandler,reportError,reportStackOverflow,reportHeapOverflow,sharedCAF)whereimportForeignimportForeign.CimportData.TypeableimportData.MaybeimportGHC.Baseimport{-# SOURCE#-}GHC.IO.Handle(hFlush)import{-# SOURCE#-}GHC.IO.Handle.FD(stdout)importGHC.IntimportGHC.IOimportGHC.IO.Encoding.UTF8importGHC.IO.ExceptionimportGHC.ExceptionimportqualifiedGHC.ForeignimportGHC.IORefimportGHC.MVarimportGHC.PtrimportGHC.Real(fromIntegral)importGHC.Show(Show(..),showString)importGHC.Stable(StablePtr(..))importGHC.Weakinfixr0`par`,`pseq`------------------------------------------------------------------------------- 'ThreadId', 'par', and 'fork'-----------------------------------------------------------------------------dataThreadId=ThreadIdThreadId#-- ToDo: data ThreadId = ThreadId (Weak ThreadId#)-- But since ThreadId# is unlifted, the Weak type must use open-- type variables.{- ^A 'ThreadId' is an abstract type representing a handle to a thread.'ThreadId' is an instance of 'Eq', 'Ord' and 'Show', wherethe 'Ord' instance implements an arbitrary total ordering over'ThreadId's. The 'Show' instance lets you convert an arbitrary-valued'ThreadId' to string form; showing a 'ThreadId' value is occasionallyuseful when debugging or diagnosing the behaviour of a concurrentprogram./Note/: in GHC, if you have a 'ThreadId', you essentially havea pointer to the thread itself.  This means the thread itself can\'t begarbage collected until you drop the 'ThreadId'.This misfeature will hopefully be corrected at a later date.-}-- | @since 4.2.0.0instanceShowThreadIdwhereshowsPrecdt=showString"ThreadId ".showsPrecd(getThreadId(id2TSOt))foreignimportccallunsafe"rts_getThreadId"getThreadId::ThreadId#->CIntid2TSO::ThreadId->ThreadId#id2TSO(ThreadIdt)=tforeignimportccallunsafe"cmp_thread"cmp_thread::ThreadId#->ThreadId#->CInt-- Returns -1, 0, 1cmpThread::ThreadId->ThreadId->OrderingcmpThreadt1t2=casecmp_thread(id2TSOt1)(id2TSOt2)of-1->LT0->EQ_->GT-- must be 1-- | @since 4.2.0.0instanceEqThreadIdwheret1==t2=caset1`cmpThread`t2ofEQ->True_->False-- | @since 4.2.0.0instanceOrdThreadIdwherecompare=cmpThread-- | Every thread has an allocation counter that tracks how much-- memory has been allocated by the thread.  The counter is-- initialized to zero, and 'setAllocationCounter' sets the current-- value.  The allocation counter counts *down*, so in the absence of-- a call to 'setAllocationCounter' its value is the negation of the-- number of bytes of memory allocated by the thread.---- There are two things that you can do with this counter:---- * Use it as a simple profiling mechanism, with--   'getAllocationCounter'.---- * Use it as a resource limit.  See 'enableAllocationLimit'.---- Allocation accounting is accurate only to about 4Kbytes.---- @since 4.8.0.0setAllocationCounter::Int64->IO()setAllocationCounter(I64#i)=IO$\s->casesetThreadAllocationCounter#isofs'->(#s',()#)-- | Return the current value of the allocation counter for the-- current thread.---- @since 4.8.0.0getAllocationCounter::IOInt64getAllocationCounter=IO$\s->casegetThreadAllocationCounter#sof(#s',ctr#)->(#s',I64#ctr#)-- | Enables the allocation counter to be treated as a limit for the-- current thread.  When the allocation limit is enabled, if the-- allocation counter counts down below zero, the thread will be sent-- the 'AllocationLimitExceeded' asynchronous exception.  When this-- happens, the counter is reinitialised (by default-- to 100K, but tunable with the @+RTS -xq@ option) so that it can handle-- the exception and perform any necessary clean up.  If it exhausts-- this additional allowance, another 'AllocationLimitExceeded' exception-- is sent, and so forth.  Like other asynchronous exceptions, the-- 'AllocationLimitExceeded' exception is deferred while the thread is inside-- 'mask' or an exception handler in 'catch'.---- Note that memory allocation is unrelated to /live memory/, also-- known as /heap residency/.  A thread can allocate a large amount of-- memory and retain anything between none and all of it.  It is-- better to think of the allocation limit as a limit on-- /CPU time/, rather than a limit on memory.---- Compared to using timeouts, allocation limits don't count time-- spent blocked or in foreign calls.---- @since 4.8.0.0enableAllocationLimit::IO()enableAllocationLimit=doThreadIdt<-myThreadIdrts_enableThreadAllocationLimitt-- | Disable allocation limit processing for the current thread.---- @since 4.8.0.0disableAllocationLimit::IO()disableAllocationLimit=doThreadIdt<-myThreadIdrts_disableThreadAllocationLimittforeignimportccallunsafe"rts_enableThreadAllocationLimit"rts_enableThreadAllocationLimit::ThreadId#->IO()foreignimportccallunsafe"rts_disableThreadAllocationLimit"rts_disableThreadAllocationLimit::ThreadId#->IO(){- |Creates a new thread to run the 'IO' computation passed as thefirst argument, and returns the 'ThreadId' of the newly createdthread.The new thread will be a lightweight, /unbound/ thread.  Foreign callsmade by this thread are not guaranteed to be made by any particular OSthread; if you need foreign calls to be made by a particular OSthread, then use 'Control.Concurrent.forkOS' instead.The new thread inherits the /masked/ state of the parent (see'Control.Exception.mask').The newly created thread has an exception handler that discards theexceptions 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', and'ThreadKilled', and passes all other exceptions to the uncaughtexception handler.-}forkIO::IO()->IOThreadIdforkIOaction=IO$\s->case(fork#action_pluss)of(#s1,tid#)->(#s1,ThreadIdtid#)where-- We must use 'catch' rather than 'catchException' because the action-- could be bottom. #13330action_plus=catchactionchildHandler-- | Like 'forkIO', but the child thread is passed a function that can-- be used to unmask asynchronous exceptions.  This function is-- typically used in the following way---- >  ... mask_ $ forkIOWithUnmask $ \unmask ->-- >                 catch (unmask ...) handler---- so that the exception handler in the child thread is established-- with asynchronous exceptions masked, meanwhile the main body of-- the child thread is executed in the unmasked state.---- Note that the unmask function passed to the child thread should-- only be used in that thread; the behaviour is undefined if it is-- invoked in a different thread.---- @since 4.4.0.0forkIOWithUnmask::((foralla.IOa->IOa)->IO())->IOThreadIdforkIOWithUnmaskio=forkIO(iounsafeUnmask){- |Like 'forkIO', but lets you specify on which capability the threadshould run.  Unlike a `forkIO` thread, a thread created by `forkOn`will stay on the same capability for its entire lifetime (`forkIO`threads can migrate between capabilities according to the schedulingpolicy).  `forkOn` is useful for overriding the scheduling policy whenyou know in advance how best to distribute the threads.The `Int` argument specifies a /capability number/ (see'getNumCapabilities').  Typically capabilities correspond to physicalprocessors, but the exact behaviour is implementation-dependent.  Thevalue passed to 'forkOn' is interpreted modulo the total number ofcapabilities as returned by 'getNumCapabilities'.GHC note: the number of capabilities is specified by the @+RTS -N@option when the program is started.  Capabilities can be fixed toactual processor cores with @+RTS -qa@ if the underlying operatingsystem supports that, although in practice this is usually unnecessary(and may actually degrade performance in some cases - experimentationis recommended).@since 4.4.0.0-}forkOn::Int->IO()->IOThreadIdforkOn(I#cpu)action=IO$\s->case(forkOn#cpuaction_pluss)of(#s1,tid#)->(#s1,ThreadIdtid#)where-- We must use 'catch' rather than 'catchException' because the action-- could be bottom. #13330action_plus=catchactionchildHandler-- | Like 'forkIOWithUnmask', but the child thread is pinned to the-- given CPU, as with 'forkOn'.---- @since 4.4.0.0forkOnWithUnmask::Int->((foralla.IOa->IOa)->IO())->IOThreadIdforkOnWithUnmaskcpuio=forkOncpu(iounsafeUnmask)-- | the value passed to the @+RTS -N@ flag.  This is the number of-- Haskell threads that can run truly simultaneously at any given-- time, and is typically set to the number of physical processor cores on-- the machine.---- Strictly speaking it is better to use 'getNumCapabilities', because-- the number of capabilities might vary at runtime.--numCapabilities::IntnumCapabilities=unsafePerformIO$getNumCapabilities{- |Returns the number of Haskell threads that can run trulysimultaneously (on separate physical processors) at any given time.  To changethis value, use 'setNumCapabilities'.@since 4.4.0.0-}getNumCapabilities::IOIntgetNumCapabilities=don<-peekenabled_capabilitiesreturn(fromIntegraln){- |Set the number of Haskell threads that can run truly simultaneously(on separate physical processors) at any given time.  The numberpassed to `forkOn` is interpreted modulo this value.  The initialvalue is given by the @+RTS -N@ runtime flag.This is also the number of threads that will participate in parallelgarbage collection.  It is strongly recommended that the number ofcapabilities is not set larger than the number of physical processorcores, and it may often be beneficial to leave one or more cores freeto avoid contention with other processes in the machine.@since 4.5.0.0-}setNumCapabilities::Int->IO()setNumCapabilitiesi|i<=0=fail$"setNumCapabilities: Capability count ("++showi++") must be positive"|otherwise=c_setNumCapabilities(fromIntegrali)foreignimportccallsafe"setNumCapabilities"c_setNumCapabilities::CUInt->IO()-- | Returns the number of CPUs that the machine has---- @since 4.5.0.0getNumProcessors::IOIntgetNumProcessors=fmapfromIntegralc_getNumberOfProcessorsforeignimportccallunsafe"getNumberOfProcessors"c_getNumberOfProcessors::IOCUInt-- | Returns the number of sparks currently in the local spark poolnumSparks::IOIntnumSparks=IO$\s->casenumSparks#sof(#s',n#)->(#s',I#n#)foreignimportccall"&enabled_capabilities"enabled_capabilities::PtrCIntchildHandler::SomeException->IO()childHandlererr=catch(real_handlererr)childHandler-- We must use catch here rather than catchException. If the-- raised exception throws an (imprecise) exception, then real_handler err-- will do so as well. If we use catchException here, then we could miss-- that exception.real_handler::SomeException->IO()real_handlerse|JustBlockedIndefinitelyOnMVar<-fromExceptionse=return()|JustBlockedIndefinitelyOnSTM<-fromExceptionse=return()|JustThreadKilled<-fromExceptionse=return()|JustStackOverflow<-fromExceptionse=reportStackOverflow|otherwise=reportErrorse{- | 'killThread' raises the 'ThreadKilled' exception in the giventhread (GHC only).> killThread tid = throwTo tid ThreadKilled-}killThread::ThreadId->IO()killThreadtid=throwTotidThreadKilled{- | 'throwTo' raises an arbitrary exception in the target thread (GHC only).Exception delivery synchronizes between the source and target thread:'throwTo' does not return until the exception has been raised in thetarget thread. The calling thread can thus be certain that the targetthread has received the exception.  Exception delivery is also atomicwith respect to other exceptions. Atomicity is a useful property to havewhen dealing with race conditions: e.g. if there are two threads thatcan kill each other, it is guaranteed that only one of the threadswill get to kill the other.Whatever work the target thread was doing when the exception wasraised is not lost: the computation is suspended until required byanother thread.If the target thread is currently making a foreign call, then theexception will not be raised (and hence 'throwTo' will not return)until the call has completed.  This is the case regardless of whetherthe call is inside a 'mask' or not.  However, in GHC a foreign callcan be annotated as @interruptible@, in which case a 'throwTo' willcause the RTS to attempt to cause the call to return; see the GHCdocumentation for more details.Important note: the behaviour of 'throwTo' differs from that described inthe paper \"Asynchronous exceptions in Haskell\"(<http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm>).In the paper, 'throwTo' is non-blocking; but the library implementation adoptsa more synchronous design in which 'throwTo' does not return until the exceptionis received by the target thread.  The trade-off is discussed in Section 9 of the paper.Like any blocking operation, 'throwTo' is therefore interruptible (see Section 5.3 ofthe paper).  Unlike other interruptible operations, however, 'throwTo'is /always/ interruptible, even if it does not actually block.There is no guarantee that the exception will be delivered promptly,although the runtime will endeavour to ensure that arbitrarydelays don't occur.  In GHC, an exception can only be raised when athread reaches a /safe point/, where a safe point is where memoryallocation occurs.  Some loops do not perform any memory allocationinside the loop and therefore cannot be interrupted by a 'throwTo'.If the target of 'throwTo' is the calling thread, then the behaviouris the same as 'Control.Exception.throwIO', except that the exceptionis thrown as an asynchronous exception.  This means that if there isan enclosing pure computation, which would be the case if the currentIO operation is inside 'unsafePerformIO' or 'unsafeInterleaveIO', thatcomputation is not permanently replaced by the exception, but issuspended as if it had received an asynchronous exception.Note that if 'throwTo' is called with the current thread as thetarget, the exception will be thrown even if the thread is currentlyinside 'mask' or 'uninterruptibleMask'.  -}throwTo::Exceptione=>ThreadId->e->IO()throwTo(ThreadIdtid)ex=IO$\s->case(killThread#tid(toExceptionex)s)ofs1->(#s1,()#)-- | Returns the 'ThreadId' of the calling thread (GHC only).myThreadId::IOThreadIdmyThreadId=IO$\s->case(myThreadId#s)of(#s1,tid#)->(#s1,ThreadIdtid#)-- | The 'yield' action allows (forces, in a co-operative multitasking-- implementation) a context-switch to any other currently runnable-- threads (if any), and is occasionally useful when implementing-- concurrency abstractions.yield::IO()yield=IO$\s->case(yield#s)ofs1->(#s1,()#){- | 'labelThread' stores a string as identifier for this thread ifyou built a RTS with debugging support. This identifier will be used inthe debugging output to make distinction of different threads easier(otherwise you only have the thread state object\'s address in the heap).Other applications like the graphical Concurrent Haskell Debugger(<http://www.informatik.uni-kiel.de/~fhu/chd/>) may choose to overload'labelThread' for their purposes as well.-}labelThread::ThreadId->String->IO()labelThread(ThreadIdt)str=GHC.Foreign.withCStringutf8str$\(Ptrp)->IO$\s->caselabelThread#tpsofs1->(#s1,()#)--      Nota Bene: 'pseq' used to be 'seq'--                 but 'seq' is now defined in PrelGHC---- "pseq" is defined a bit weirdly (see below)---- The reason for the strange "lazy" call is that-- it fools the compiler into thinking that pseq  and par are non-strict in-- their second argument (even if it inlines pseq at the call site).-- If it thinks pseq is strict in "y", then it often evaluates-- "y" before "x", which is totally wrong.{-# INLINEpseq#-}pseq::a->b->bpseqxy=x`seq`lazyy{-# INLINEpar#-}par::a->b->bparxy=case(par#x)of{_->lazyy}-- | Internal function used by the RTS to run sparks.runSparks::IO()runSparks=IOloopwhereloops=casegetSpark#sof(#s',n,p#)->ifisTrue#(n==#0#)then(#s',()#)elsep`seq`loops'dataBlockReason=BlockedOnMVar-- ^blocked on 'MVar'{- possibly (see 'threadstatus' below):  | BlockedOnMVarRead        -- ^blocked on reading an empty 'MVar'  -}|BlockedOnBlackHole-- ^blocked on a computation in progress by another thread|BlockedOnException-- ^blocked in 'throwTo'|BlockedOnSTM-- ^blocked in 'retry' in an STM transaction|BlockedOnForeignCall-- ^currently in a foreign call|BlockedOnOther-- ^blocked on some other resource.  Without @-threaded@,-- I\/O and 'threadDelay' show up as 'BlockedOnOther', with @-threaded@-- they show up as 'BlockedOnMVar'.deriving(Eq-- ^ @since 4.3.0.0,Ord-- ^ @since 4.3.0.0,Show-- ^ @since 4.3.0.0)-- | The current status of a threaddataThreadStatus=ThreadRunning-- ^the thread is currently runnable or running|ThreadFinished-- ^the thread has finished|ThreadBlockedBlockReason-- ^the thread is blocked on some resource|ThreadDied-- ^the thread received an uncaught exceptionderiving(Eq-- ^ @since 4.3.0.0,Ord-- ^ @since 4.3.0.0,Show-- ^ @since 4.3.0.0)threadStatus::ThreadId->IOThreadStatusthreadStatus(ThreadIdt)=IO$\s->casethreadStatus#tsof(#s',stat,_cap,_locked#)->(#s',mk_stat(I#stat)#)where-- NB. keep these in sync with includes/rts/Constants.hmk_stat0=ThreadRunningmk_stat1=ThreadBlockedBlockedOnMVarmk_stat2=ThreadBlockedBlockedOnBlackHolemk_stat6=ThreadBlockedBlockedOnSTMmk_stat10=ThreadBlockedBlockedOnForeignCallmk_stat11=ThreadBlockedBlockedOnForeignCallmk_stat12=ThreadBlockedBlockedOnExceptionmk_stat14=ThreadBlockedBlockedOnMVar-- possibly: BlockedOnMVarRead-- NB. these are hardcoded in rts/PrimOps.cmmmk_stat16=ThreadFinishedmk_stat17=ThreadDiedmk_stat_=ThreadBlockedBlockedOnOther-- | Returns the number of the capability on which the thread is currently-- running, and a boolean indicating whether the thread is locked to-- that capability or not.  A thread is locked to a capability if it-- was created with @forkOn@.---- @since 4.4.0.0threadCapability::ThreadId->IO(Int,Bool)threadCapability(ThreadIdt)=IO$\s->casethreadStatus#tsof(#s',_,cap#,locked##)->(#s',(I#cap#,isTrue#(locked#/=#0#))#)-- | Make a weak pointer to a 'ThreadId'.  It can be important to do-- this if you want to hold a reference to a 'ThreadId' while still-- allowing the thread to receive the @BlockedIndefinitely@ family of-- exceptions (e.g. 'BlockedIndefinitelyOnMVar').  Holding a normal-- 'ThreadId' reference will prevent the delivery of-- @BlockedIndefinitely@ exceptions because the reference could be-- used as the target of 'throwTo' at any time, which would unblock-- the thread.---- Holding a @Weak ThreadId@, on the other hand, will not prevent the-- thread from receiving @BlockedIndefinitely@ exceptions.  It is-- still possible to throw an exception to a @Weak ThreadId@, but the-- caller must use @deRefWeak@ first to determine whether the thread-- still exists.---- @since 4.6.0.0mkWeakThreadId::ThreadId->IO(WeakThreadId)mkWeakThreadIdt@(ThreadIdt#)=IO$\s->casemkWeakNoFinalizer#t#tsof(#s1,w#)->(#s1,Weakw#)dataPrimMVar-- | Make a StablePtr that can be passed to the C function-- @hs_try_putmvar()@.  The RTS wants a 'StablePtr' to the underlying-- 'MVar#', but a 'StablePtr#' can only refer to lifted types, so we-- have to cheat by coercing.newStablePtrPrimMVar::MVar()->IO(StablePtrPrimMVar)newStablePtrPrimMVar(MVarm)=IO$\s0->casemakeStablePtr#(unsafeCoerce#m::PrimMVar)s0of(#s1,sp#)->(#s1,StablePtrsp#)------------------------------------------------------------------------------- Transactional heap operations------------------------------------------------------------------------------- TVars are shared memory locations which support atomic memory-- transactions.-- |A monad supporting atomic memory transactions.newtypeSTMa=STM(State#RealWorld->(#State#RealWorld,a#))unSTM::STMa->(State#RealWorld->(#State#RealWorld,a#))unSTM(STMa)=a-- | @since 4.3.0.0instanceFunctorSTMwherefmapfx=x>>=(pure.f)-- | @since 4.8.0.0instanceApplicativeSTMwhere{-# INLINEpure#-}{-# INLINE(*>)#-}{-# INLINEliftA2#-}purex=returnSTMx(<*>)=apliftA2=liftM2m*>k=thenSTMmk-- | @since 4.3.0.0instanceMonadSTMwhere{-# INLINE(>>=)#-}m>>=k=bindSTMmk(>>)=(*>)bindSTM::STMa->(a->STMb)->STMbbindSTM(STMm)k=STM(\s->casemsof(#new_s,a#)->unSTM(ka)new_s)thenSTM::STMa->STMb->STMbthenSTM(STMm)k=STM(\s->casemsof(#new_s,_#)->unSTMknew_s)returnSTM::a->STMareturnSTMx=STM(\s->(#s,x#))-- | @since 4.8.0.0instanceAlternativeSTMwhereempty=retry(<|>)=orElse-- | @since 4.3.0.0instanceMonadPlusSTM-- | Unsafely performs IO in the STM monad.  Beware: this is a highly-- dangerous thing to do.----   * The STM implementation will often run transactions multiple--     times, so you need to be prepared for this if your IO has any--     side effects.----   * The STM implementation will abort transactions that are known to--     be invalid and need to be restarted.  This may happen in the middle--     of `unsafeIOToSTM`, so make sure you don't acquire any resources--     that need releasing (exception handlers are ignored when aborting--     the transaction).  That includes doing any IO using Handles, for--     example.  Getting this wrong will probably lead to random deadlocks.----   * The transaction may have seen an inconsistent view of memory when--     the IO runs.  Invariants that you expect to be true throughout--     your program may not be true inside a transaction, due to the--     way transactions are implemented.  Normally this wouldn't be visible--     to the programmer, but using `unsafeIOToSTM` can expose it.--unsafeIOToSTM::IOa->STMaunsafeIOToSTM(IOm)=STMm-- | Perform a series of STM actions atomically.---- Using 'atomically' inside an 'unsafePerformIO' or 'unsafeInterleaveIO'-- subverts some of guarantees that STM provides. It makes it possible to-- run a transaction inside of another transaction, depending on when the-- thunk is evaluated. If a nested transaction is attempted, an exception-- is thrown by the runtime. It is possible to safely use 'atomically' inside-- 'unsafePerformIO' or 'unsafeInterleaveIO', but the typechecker does not-- rule out programs that may attempt nested transactions, meaning that-- the programmer must take special care to prevent these.---- However, there are functions for creating transactional variables that-- can always be safely called in 'unsafePerformIO'. See: 'newTVarIO',-- 'newTChanIO', 'newBroadcastTChanIO', 'newTQueueIO', 'newTBQueueIO',-- and 'newTMVarIO'.---- Using 'unsafePerformIO' inside of 'atomically' is also dangerous but for-- different reasons. See 'unsafeIOToSTM' for more on this.atomically::STMa->IOaatomically(STMm)=IO(\s->(atomically#m)s)-- | Retry execution of the current memory transaction because it has seen-- values in 'TVar's which mean that it should not continue (e.g. the 'TVar's-- represent a shared buffer that is now empty).  The implementation may-- block the thread until one of the 'TVar's that it has read from has been-- updated. (GHC only)retry::STMaretry=STM$\s#->retry#s#-- | Compose two alternative STM actions (GHC only).---- If the first action completes without retrying then it forms the result of-- the 'orElse'. Otherwise, if the first action retries, then the second action-- is tried in its place. If both actions retry then the 'orElse' as a whole-- retries.orElse::STMa->STMa->STMaorElse(STMm)e=STM$\s->catchRetry#m(unSTMe)s-- | A variant of 'throw' that can only be used within the 'STM' monad.---- Throwing an exception in @STM@ aborts the transaction and propagates the-- exception.---- Although 'throwSTM' has a type that is an instance of the type of 'throw', the-- two functions are subtly different:---- > throw e    `seq` x  ===> throw e-- > throwSTM e `seq` x  ===> x---- The first example will cause the exception @e@ to be raised,-- whereas the second one won\'t.  In fact, 'throwSTM' will only cause-- an exception to be raised when it is used within the 'STM' monad.-- The 'throwSTM' variant should be used in preference to 'throw' to-- raise an exception within the 'STM' monad because it guarantees-- ordering with respect to other 'STM' operations, whereas 'throw'-- does not.throwSTM::Exceptione=>e->STMathrowSTMe=STM$raiseIO#(toExceptione)-- |Exception handling within STM actions.catchSTM::Exceptione=>STMa->(e->STMa)->STMacatchSTM(STMm)handler=STM$catchSTM#mhandler'wherehandler'e=casefromExceptioneofJuste'->unSTM(handlere')Nothing->raiseIO#e-- |Shared memory locations that support atomic memory transactions.dataTVara=TVar(TVar#RealWorlda)-- | @since 4.8.0.0instanceEq(TVara)where(TVartvar1#)==(TVartvar2#)=isTrue#(sameTVar#tvar1#tvar2#)-- | Create a new 'TVar' holding a value suppliednewTVar::a->STM(TVara)newTVarval=STM$\s1#->casenewTVar#vals1#of(#s2#,tvar##)->(#s2#,TVartvar##)-- | @IO@ version of 'newTVar'.  This is useful for creating top-level-- 'TVar's using 'System.IO.Unsafe.unsafePerformIO', because using-- 'atomically' inside 'System.IO.Unsafe.unsafePerformIO' isn't-- possible.newTVarIO::a->IO(TVara)newTVarIOval=IO$\s1#->casenewTVar#vals1#of(#s2#,tvar##)->(#s2#,TVartvar##)-- | Return the current value stored in a 'TVar'.-- This is equivalent to---- >  readTVarIO = atomically . readTVar---- but works much faster, because it doesn't perform a complete-- transaction, it just reads the current value of the 'TVar'.readTVarIO::TVara->IOareadTVarIO(TVartvar#)=IO$\s#->readTVarIO#tvar#s#-- |Return the current value stored in a 'TVar'.readTVar::TVara->STMareadTVar(TVartvar#)=STM$\s#->readTVar#tvar#s#-- |Write the supplied value into a 'TVar'.writeTVar::TVara->a->STM()writeTVar(TVartvar#)val=STM$\s1#->casewriteTVar#tvar#vals1#ofs2#->(#s2#,()#)------------------------------------------------------------------------------- MVar utilities------------------------------------------------------------------------------- | Provide an 'IO' action with the current value of an 'MVar'. The 'MVar'-- will be empty for the duration that the action is running.withMVar::MVara->(a->IOb)->IObwithMVarmio=mask$\restore->doa<-takeMVarmb<-catchAny(restore(ioa))(\e->doputMVarma;throwe)putMVarmareturnb-- | Modify the value of an 'MVar'.modifyMVar_::MVara->(a->IOa)->IO()modifyMVar_mio=mask$\restore->doa<-takeMVarma'<-catchAny(restore(ioa))(\e->doputMVarma;throwe)putMVarma'return()------------------------------------------------------------------------------- Thread waiting------------------------------------------------------------------------------- Machinery needed to ensure that we only have one copy of certain-- CAFs in this module even when the base package is present twice, as-- it is when base is dynamically loaded into GHCi.  The RTS keeps-- track of the single true value of the CAF, so even when the CAFs in-- the dynamically-loaded base package are reverted, nothing bad-- happens.--sharedCAF::a->(Ptra->IO(Ptra))->IOasharedCAFaget_or_set=mask_$dostable_ref<-newStablePtraletref=castPtr(castStablePtrToPtrstable_ref)ref2<-get_or_setrefifref==ref2thenreturnaelsedofreeStablePtrstable_refdeRefStablePtr(castPtrToStablePtr(castPtrref2))reportStackOverflow::IO()reportStackOverflow=doThreadIdtid<-myThreadIdc_reportStackOverflowtidreportError::SomeException->IO()reportErrorex=dohandler<-getUncaughtExceptionHandlerhandlerex-- SUP: Are the hooks allowed to re-enter Haskell land?  If so, remove-- the unsafe below.foreignimportccallunsafe"reportStackOverflow"c_reportStackOverflow::ThreadId#->IO()foreignimportccallunsafe"reportHeapOverflow"reportHeapOverflow::IO(){-# NOINLINEuncaughtExceptionHandler#-}uncaughtExceptionHandler::IORef(SomeException->IO())uncaughtExceptionHandler=unsafePerformIO(newIORefdefaultHandler)wheredefaultHandler::SomeException->IO()defaultHandlerse@(SomeExceptionex)=do(hFlushstdout)`catchAny`(\_->return())letmsg=casecastexofJustDeadlock->"no threads to run:  infinite loop or deadlock?"_->showsPrec0se""withCString"%s"$\cfmt->withCStringmsg$\cmsg->errorBelchcfmtcmsg-- don't use errorBelch() directly, because we cannot call varargs functions-- using the FFI.foreignimportccallunsafe"HsBase.h errorBelch2"errorBelch::CString->CString->IO()setUncaughtExceptionHandler::(SomeException->IO())->IO()setUncaughtExceptionHandler=writeIORefuncaughtExceptionHandlergetUncaughtExceptionHandler::IO(SomeException->IO())getUncaughtExceptionHandler=readIORefuncaughtExceptionHandler

[8]ページ先頭

©2009-2025 Movatter.jp