| 68 | | Bound threads allow a Haskell program more control over the mapping between Haskell threads and OS threads. Such control is required for interacting with foreign code that is either single-threaded or makes use of thread-local state in the native OS threading model. |
| | 73 | Bound threads allow a Haskell program more control over the mapping between Haskell threads and OS threads. Such control is required for interacting with foreign code that makes use of thread-local state in the native OS threading model. When foreign code uses OS thread-local state, the Haskell programmer needs to restrict calls to that foreign code to happen in a particular OS thread, which is what bound threads provide. |
| | 74 | |
| | 75 | Bound threads are an optional feature in Haskell'; the documentation for an implementation should state whether bound threads are supported or not. |
| | 76 | |
| | 77 | A Haskell thread can be either ''bound'' or ''unbound'', depending on how it was created: |
| | 78 | |
| | 79 | * Calls from foreign code to Haskell functions exposed by `foreign export` or `foreign import "wrapper"` create a |
| | 80 | ''bound'' thread in which to run the computation. |
| | 81 | |
| | 82 | * `forkIO` creates ''unbound'' threads |
| | 83 | |
| | 84 | Whether a thread is bound or unbound affects how foreign calls are made: |
| | 85 | |
| | 86 | * Foreign calls made by an unbound thread happen in an arbitrary OS thread. |
| | 87 | |
| | 88 | * Foreign calls made by a bound thread are always made by the OS thread that made the original call-in. |
| | 89 | |
| | 90 | Note that a valid implementation of bound threads is one in which every Haskell thread is associated with a distinct OS thread, where in effect every thread is bound. However, the `isCurrentThreadBound` operation (see below) should always return `False` for threads created by `forkIO`, regardless of the implementation, to aid portabilty. |
| | 91 | |
| | 92 | The following operations exported by `Control.Concurrent` are related to bound threads: |
| | 93 | |
| | 94 | {{{ |
| | 95 | supportsBoundThreads :: Bool |
| | 96 | }}} |
| | 97 | |
| | 98 | This value is `True` if the implementation supports bound threads ('''NB.''' this is called `rtsSupportsBoundThreads` currently). |
| | 99 | |
| | 100 | {{{ |
| | 101 | isCurrentThreadBound :: IO Bool |
| | 102 | }}} |
| | 103 | |
| | 104 | This operation returns `False` if the current thread was created by `forkIO`, and `True` otherwise. |
| | 105 | |
| | 106 | {{{ |
| | 107 | forkOS :: IO () -> IO ThreadId |
| | 108 | }}} |
| | 109 | |
| | 110 | Like `forkIO`, `forkOS` creates a new Haskell thread to run the supplied `IO` action. However, in the case of `forkOS`, the new Haskell thread is bound to a freshly created OS thread. This is achieved by making a foreign call to create the new OS thread, and having the new OS thread invoke the `IO` action, thus creating a bound thread. |