ng Q      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI J K L M N O P XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com>Like Q, but not bounded by an R. KSuspends the current thread for a given number of microseconds (GHC only). LThere is no guarantee that the thread will be rescheduled promptly when the Jdelay has expired, but the thread will never continue to run earlier than  specified. XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com>STLike U, but not bounded by an R. Wrap an V$ computation to time out and return W in case no result is available within n microseconds (1/10^6 seconds). In case a result is &available before the timeout expires, X a! is returned. A negative timeout interval means "wait indefinitely". ?The design of this combinator was guided by the objective that  timeout n f "should behave exactly the same as f as long as f doesn't time out. This  means that f has the same Y# it would have without the timeout wrapper. Any exceptions f6 might throw cancel the timeout and propagate further up. It also possible for f/ to receive exceptions thrown to it by another thread. BA tricky implementation detail is the question of how to abort an V Pcomputation. This combinator relies on asynchronous exceptions internally. The Ktechnique works very well for computations executing inside of the Haskell runtime system, but it doesn',t work at all for non-Haskell code. Foreign Mfunction calls, for example, cannot be timed out with this combinator simply Mbecause an arbitrary C function cannot receive asynchronous exceptions. When timeoutB is used to wrap an FFI call that blocks, no timeout event can be Odelivered until the FFI call returns, which pretty much negates the purpose of Qthe combinator. In practice, however, this limitation is less severe than it may sound. Standard I/O functions like Z, [, Network.Socket.accept, or \ appear to be blocking, but they really don'=t because the runtime system uses scheduling mechanisms like  select(2) to perform asynchronous I/"O, so it is possible to interrupt standard socket I/ O or file I/O using this combinator.  ]^_`ab]^_`ab]^_`abXBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> .A broadcast is in one of two possible states:  "Silent": ing. to the broadcast will block until a value is ed.  " Broadcasting x": ing( to the broadcast will return the value x without blocking. cdnew Creates a broadcast in the "silent" state. newBroadcasting x Creates a broadcast in the " broadcasting x" state. Listen to a broadcast.  If the broadcast is " broadcasting x", listen will return x  immediately.  If the broadcast is "silent", listen! will block until another thread s a value to the broadcast. ,Try to listen to a broadcast; non blocking.  If the broadcast is " broadcasting x",  tryListen will return X x  immediately.  If the broadcast is "silent",  tryListen returns W immediately. HListen to a broadcast if it is available within a given amount of time. Like (, but with a timeout. A return value of W indicates a timeout occurred. *The timeout is specified in microseconds. If the broadcast is "silent" and a timeout of 0 s is specified the function returns W without blocking. 9Negative timeouts are treated the same as a timeout of 0 s. Broadcast a value.  broadcast b x$ changes the state of the broadcast b to " broadcasting x". If the broadcast was "silent" all threads that are ing to the broadcast will be woken. "Broadcast a value before becoming "silent". )The state of the broadcast is changed to "silent" after all threads that are ingA to the broadcast are woken and resume with the signalled value. DThe semantics of signal are equivalent to the following definition:   signal b x = e $  b x >>   b Set a broadcast to the "silent" state.    XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> A   7 is an abstract type representing a handle to a thread 8that is executing or has executed a computation of type V .    is an instance of f, g and h , where the g 5instance implements an arbitrary total ordering over  s. The h .instance lets you convert an arbitrary-valued   to string form; showing a  ? value is occasionally useful when debugging or diagnosing the #behaviour of a concurrent program. ij Extract the underlying k  (Conctrol.Concurrent.ThreadId). )Sparks off a new thread to run the given V computation and returns the   of the newly created thread. JThe new thread will be a lightweight thread; if you want to use a foreign ,library that uses thread-local storage, use  instead. GGHC note: the new thread inherits the blocked state of the parent (see e). OThe newly created thread has an exception handler that discards the exceptions l, m, and n. All %other exceptions are recorded in the   and can be retrieved using . Like  0, this sparks off a new thread to run the given V computation and returns the   of the newly created thread. Unlike  ,  creates a bound# thread, which is necessary if you Kneed to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see Control.Concurrent). Using  instead of  . makes no difference at all to the scheduling Obehaviour of the Haskell runtime system. It is a common misconception that you  need to use  instead of  # to avoid blocking all the Haskell ,threads when making a foreign call; this isn'#t the case. To allow foreign calls Kto be made without blocking all the Haskell threads (with GHC), it is only necessary to use the  -threaded/ option when linking your program, and to make &sure the foreign import is not marked unsafe. o+Internally used function which generalises   and . Parametrised /by the function which does the actual forking. ,Block until the given thread is terminated.  Returns p x0 if the thread terminated normally and returned x.  Returns q e if some exception e" was thrown in the thread and wasn't caught. Like 3 but will ignore the value returned by the thread. Like > but will either rethrow the exception that was thrown in the = thread or return the value that was returned by the thread. Like : in that it will rethrow the exception that was thrown in A the thread but it will ignore the value returned by the thread. EBlock until the given thread is terminated or until a timer expires.  Returns W if a timeout occurred.  Returns X the result . would return when the thread finished within the specified time. *The timeout is specified in microseconds. Like 3 but will ignore the value returned by the thread.  Returns r when a timeout occurred and s otherwise. Like 7 but will rethrow the exception that was thrown in the thread. Returns W if a timeout occured or X the value returned from the target thread. Like 0 in that it will rethrow the exception that was K thrown in the thread but it will ignore the value returned by the thread.  Returns r when a timeout occurred and s otherwise. Returns s+ if the given thread is currently running. ;Notice that this observation is only a snapshot of a thread's state. By the time >a program reacts on its result it may already be out of date. @ raises an arbitrary exception in the target thread (GHC only). C does not return until the exception has been raised in the target Jthread. The calling thread can thus be certain that the target thread has Qreceived the exception. This is a useful property to know when dealing with race Iconditions: eg. if there are two threads that can kill each other, it is Dguaranteed that only one of the threads will get to kill the other. QIf the target thread is currently making a foreign call, then the exception will not be raised (and hence % will not return) until the call has Gcompleted. This is the case regardless of whether the call is inside a e or not. !Important note: the behaviour of $ differs from that described in the paper ""Asynchronous exceptions in Haskell" ( =http://research.microsoft.com/~simonpj/Papers/asynch-exns.htm). In the paper, ? is non-blocking; but the library implementation adopts a more synchronous design in which ( does not return until the exception is Nreceived by the target thread. The trade-off is discussed in Section 9 of the $paper. Like any blocking operation, ! is therefore interruptible (see Section 5.3 of the paper). @There is currently no guarantee that the exception delivered by  will Lbe delivered at the first possible opportunity. In particular, a thread may t and then re-e( exceptions without receiving a pending *. This is arguably undesirable behaviour. B terminates the given thread (GHC only). Any work already done by the thread isn'?t lost: the computation is suspended until required by another Ithread. The memory used by the thread will be garbage collected if it isn't referenced from anywhere. The ! function is defined in terms of . QThis function blocks until the target thread is terminated. It is a no-op if the %target thread has already completed. Like  but with a timeout. Returns s if the target thread was ,terminated within the given amount of time, r otherwise. *The timeout is specified in microseconds. QNote that even when a timeout occurs, the target thread can still terminate at a 8later time as a direct result of calling this function.     XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> +An event is in one of two possible states: "set" or "cleared". uvCreate an event in the "cleared" state. Create an event in the "set" state. Block until the event is !. %If the state of the event is already "set" this function will return @immediately. Otherwise it will block until another thread calls !. J(You can also resume a thread that is waiting for an event by throwing an asynchronous exception.) Block until the event is ! or until a timer expires. Like (, but with a timeout. A return value of r indicates a timeout  occurred. *The timeout is specified in microseconds. If the event is "cleared" and a timeout of 0 s is specified the function returns r without blocking. 9Negative timeouts are treated the same as a timeout of 0 s. Returns s if the state of the event is "set" and r if the state is "cleared". ONotice that this is only a snapshot of the state. By the time a program reacts -on its result it may already be out of date. !"Changes the state of the event to "set"!. All threads that where waiting 'for this event are woken. Threads that  after the state is changed to "set" will not block at all. "Changes the state to "cleared"/ after all threads that where waiting for this event are woken. Threads that  after a signal will block until the event is ! again. DThe semantics of signal are equivalent to the following definition:   signal e = e $ ! e >> # e #"Changes the state of the event to "cleared". Threads that  after the state is changed to "cleared"* will block until the state is changed to "set".  !"#  !"#  !"#XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> $ A lock is in one of two states: "locked" or "unlocked". wx%Create a lock in the "unlocked" state. &Create a lock in the "locked" state. ' Acquires the $,. Blocks if another thread has acquired the $. acquire behaves as follows:  When the state is "unlocked" acquire changes the state to "locked".  When the state is "locked" acquire blocks until a call to ) in Qanother thread wakes the calling thread. Upon awakening it will change the state to "locked". .There are two further important properties of acquire:  acquireE is single-wakeup. That is, if there are multiple threads blocked on acquireA and the lock is released, only one thread will be woken up. The 7runtime guarantees that the woken thread completes its acquire operation. & When multiple threads are blocked on acquire, they are woken up in FIFO Norder. This is useful for providing fairness properties of abstractions built Nusing locks. (Note that this differs from the Python implementation where the wake-up order is undefined.) (A non-blocking '.  When the state is "unlocked"  tryAcquire changes the state to "locked"  and returns True.  When the state is "locked"  tryAcquire leaves the state unchanged and returns False. )release changes the state to "unlocked" and returns immediately. 2Note that it is an error to release a lock in the "unlocked" state! $If there are any threads blocked on ' the thread that first called acquire will be woken up. *KA convenience function which first acquires the lock and then performs the Pcomputation. When the computation terminates, whether normally or by raising an !exception, the lock is released.  Note that: with = y z ' ). +A non-blocking *. tryWith0 is a convenience function which first tries to !acquire the lock. If that fails, W" is returned. If it succeeds, the Ocomputation is performed. When the computation terminates, whether normally or 2by raising an exception, the lock is released and X the result of the computation is returned. , When the state is "locked", wait blocks until a call to ) in another thread changes it to "unlocked".  When the state is "unlocked" wait returns immediately. wait' does not alter the state of the lock.  Note that wait, is just a convenience function defined as:  wait l = e { ' l | ) l-!Determines if the lock is in the "locked" state. MNote that this is only a snapshot of the state. By the time a program reacts -on its result it may already be out of date. $%&'()*+,- $%&'()*+,- $%&'()*+,-XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> .The state of an /.  W indicates an "unlocked" state.  X (tid, n) indicates a "locked"& state where the thread identified by tid acquired the lock n times. /*A reentrant lock is in one of two states: "locked" or "unlocked". When the lock is in the "locked") state it has two additional properties:  Its owner%: the thread that acquired the lock.  Its acquired count.: how many times its owner acquired the lock. }~0Create a reentrant lock in the "unlocked" state. 1Create a reentrant lock in the "locked"# state (with the current thread as #owner and an acquired count of 1). 2 Acquires the /,. Blocks if another thread has acquired the /. acquire behaves as follows:  When the state is "unlocked", acquire changes the state to "locked" =with the current thread as owner and an acquired count of 1.  When the state is "locked"& and the current thread owns the lock acquire $only increments the acquired count.  When the state is "locked". and the current thread does not own the lock acquire blocks> until the owner releases the lock. If the thread that called acquireE is woken upon release of the lock it will take ownership and change  the state to "locked" with an acquired count of 1. .There are two further important properties of acquire:  acquireE is single-wakeup. That is, if there are multiple threads blocked on acquireB, and the lock is released, only one thread will be woken up. The 7runtime guarantees that the woken thread completes its acquire operation. & When multiple threads are blocked on acquire they are woken up in FIFO Norder. This is useful for providing fairness properties of abstractions built Nusing locks. (Note that this differs from the Python implementation where the wake-up order is undefined.) 3A non-blocking 2.  When the state is "unlocked"  tryAcquire changes the state to "locked" J(with the current thread as owner and an acquired count of 1) and returns s.  When the state is "locked"  tryAcquire leaves the state unchanged and returns r. 4release@ decrements the acquired count. When a lock is released with an ,acquired count of 1 its state is changed to "unlocked". 7Note that it is both an error to release a lock in the "unlocked" state and to 8release a lock that is not owned by the current thread. $If there are any threads blocked on 2 the thread that first called acquire will be woken up. 5>A convenience function which first acquires the lock and then Cperforms the computation. When the computation terminates, whether ;normally or by raising an exception, the lock is released.  Note that: with = y z 2 4. 6A non-blocking 5. tryWith0 is a convenience function which first tries to !acquire the lock. If that fails, W" is returned. If it succeeds, the Ocomputation is performed. When the computation terminates, whether normally or 2by raising an exception, the lock is released and X the result of the computation is returned. 7 When the state is "locked" wait blocks until a call to 4 in another thread changes it to "unlocked".  When the state is "unlocked" wait returns immediately. wait' does not alter the state of the lock.  Note that wait, is just a convenience function defined as:  wait l = e { 2 l | 4 l8+Determine the state of the reentrant lock. PNote that this is only a snapshot of the state. By the time a program reacts on *its result it may already be out of date. ./012345678 /01234567.8 ./012345678XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com>Internal state of the 9. 9@Multiple-reader, single-writer lock. Is in one of three states:  "Free"9: Read or write access can be acquired without blocking.  "Read"F: One or more threads have acquired read access. Blocks write access.  "Write"B: A single thread has acquired write access. Blocks other threads +from acquiring both read and write access. : Create a new 9 in the "free"$ state; either read or write access # can be acquired without blocking. ; Create a new 9 in the "read"" state; only read can be acquired  without blocking. < Create a new 9 in the "write"! state; either acquiring read or  write will block. =Acquire the read lock. 7Blocks if another thread has acquired write access. If  acquireRead terminates /without throwing an exception the state of the 9 will be "read". JImplementation note: Throws an exception when more than (maxBound :: Int) Bsimultaneous threads acquire the read lock. But that is unlikely. >,Try to acquire the read lock; non blocking. Like = , but doesn't block. Returns s if the resulting state is "read", r otherwise. ?Release the read lock. PIf the calling thread was the last one to relinquish read access the state will  revert to "free". ,It is an error to release read access to an 9 which is not in the "read" state. @MA convenience function wich first acquires read access and then performs the Pcomputation. When the computation terminates, whether normally or by raising an &exception, the read lock is released. AA non-blocking @2. First tries to acquire the lock. If that fails, WE is returned. If it succeeds, the computation is performed. When the Qcomputation terminates, whether normally or by raising an exception, the lock is  released and X, the result of the computation is returned. B When the state is "write", waitRead blocks until a call to E( in another thread changes the state to "free".  When the state is "free" or "read" waitRead returns immediately. waitRead' does not alter the state of the lock.  Note that waitRead, is just a convenience function defined as:  waitRead l = e { = l | ? lCAcquire the write lock. FBlocks if another thread has acquired either read or write access. If  acquireWrite; terminates without throwing an exception the state of the 9 will be "write". D-Try to acquire the write lock; non blocking. Like C , but doesn't block. Returns s if the resulting state is "write", r otherwise. ERelease the write lock. If  releaseWrite< terminates without throwing an exception the state will be "free". -It is an error to release write access to an 9 which is not in the "write" state. FJA convenience function wich first acquires write access and then performs Qthe computation. When the computation terminates, whether normally or by raising *an exception, the write lock is released. GA non-blocking F2. First tries to acquire the lock. If that fails, WE is returned. If it succeeds, the computation is performed. When the Qcomputation terminates, whether normally or by raising an exception, the lock is  released and X, the result of the computation is returned. H When the state is "write" or "read"  waitWrite blocks until a call to E or ?( in another thread changes the state to "free".  When the state is "free"  waitWrite returns immediately.  waitWrite' does not alter the state of the lock.  Note that  waitWrite, is just a convenience function defined as: waitWrite l = e { C l | E l9:;<=>?@ABCDEFGH9:;<=?@B>ACEFHDG9:;<=>?@ABCDEFGH XBas van Dijk <v.dijk.bas@gmail.com> , Roel van Dijk <vandijk.roel@gmail.com> I:Concurrently readable and sequentially writable variable. J Create a new I. K7Execute an action that operates on the contents of the I. LThe action is guaranteed to have a consistent view of the stored value. Any function that attempts to N- the contents will block until the action is  completed. 3If another thread is modifying the contents of the I this function will 2block until the other thread finishes its action. LLike K but doesn't block. Returns X the result if read access $could be acquired without blocking, W otherwise. MModify the contents of an I. 2This function needs exclusive write access to the I. Only one thread can  modify an I* at the same time. All others will block. NModify the contents of an I! and return an additional value. Like M%, but allows a value to be returned () in addition to the modified value of the I. O%Attempt to modify the contents of an I. Like M , but doesn't block. Returns s if the contents could be  replaced, r otherwise. P%Attempt to modify the contents of an I! and return an additional value. Like N , but doesn't block. Returns X the additional value if the contents could be replaced, W otherwise. IJKLMNOPIJKLMNOPIJKLMNOP    !"#$%&'()*+,-./01234,-./0156789:;<=>?@ABCD E  0 1 F G H IJKLMNOPPJQ MNRJSTJSUJKVJWXJWYJWZ [ \ ] ^ _ ` aJbcJdeJdfJghiJKJjkJjlJjmnJopJoqMrsMrtJbu&v+wJxyJz{J|}J|~4w365 Econcurrent-extra-0.4Control.Concurrent.Thread.DelayControl.Concurrent.TimeoutControl.Concurrent.BroadcastControl.Concurrent.ThreadControl.Concurrent.EventControl.Concurrent.LockControl.Concurrent.RLock Control.Concurrent.ReadWriteLockControl.Concurrent.ReadWriteVarUtilsdelaytimeout BroadcastnewnewBroadcastinglisten tryListen listenTimeout broadcastsignalsilenceThreadIdthreadIdforkIOforkOSwaitwait_ unsafeWait unsafeWait_ waitTimeout waitTimeout_unsafeWaitTimeoutunsafeWaitTimeout_ isRunningthrowTo killThreadkillThreadTimeoutEventnewSetisSetsetclearLock newAcquiredacquire tryAcquirereleasewithtryWithlockedStateRLockstateRWLocknewAcquiredReadnewAcquiredWrite acquireReadtryAcquireRead releaseReadwithRead tryWithReadwaitRead acquireWritetryAcquireWrite releaseWrite withWrite tryWithWrite waitWriteRWVarmodify_modify tryModify_ tryModifybaseGHC.Conc threadDelayghc-prim GHC.TypesIntTimeoutSystem.TimeoutIO Data.MaybeNothingJust myThreadIdGHC.IO.Handle.TexthGetBufhPutBuf hWaitForInputvoidifM throwInnerpurelyModifyMVar modifyIORefM modifyIORefM_ unBroadcastGHC.IOblock GHC.ClassesEqOrdGHC.ShowShowstoppedGHC.IO.ExceptionBlockedIndefinitelyOnMVarBlockedIndefinitelyOnSTM ThreadKilledfork Data.EitherRightLeftGHC.BoolFalseTrueunblock evBroadcastunControl.ApplicativeliftA2Control.Exception.Basebracket_GHC.Base$>>WriteReadFreereadLock writeLock moduleName