[5fd5de2] | 1 | % ====================================================================== |
---|
| 2 | % ====================================================================== |
---|
| 3 | \chapter{Channels}\label{s:channels} |
---|
| 4 | % ====================================================================== |
---|
| 5 | % ====================================================================== |
---|
| 6 | |
---|
[9921573] | 7 | Most modern concurrent programming languages do not subscribe to just one style of communication among threads and provide features that support multiple approaches. |
---|
[e9fffb1] | 8 | Channels are a concurrent-language feature used to perform \Newterm{message-passing concurrency}: a model of concurrency where threads communicate by sending data as messages (mostly non\-blocking) and synchronizing by receiving sent messages (blocking). |
---|
[9f1beb4] | 9 | This model is an alternative to shared-memory concurrency, where threads communicate directly by changing shared state. |
---|
[9921573] | 10 | |
---|
[5384793] | 11 | Channels were first introduced by Kahn~\cite{Kahn74} and extended by Hoare~\cite{CSP} (CSP). |
---|
[9921573] | 12 | Both papers present a pseudo (unimplemented) concurrent language where processes communicate using input/output channels to send data. |
---|
| 13 | Both languages are highly restrictive. |
---|
| 14 | Kahn's language restricts a reading process to only wait for data on a single channel at a time and different writing processes cannot send data on the same channel. |
---|
[9f1beb4] | 15 | Hoare's language restricts both the sender and receiver to explicitly name the process that is the destination of a channel send or the source of a channel receive. |
---|
| 16 | These channel semantics remove the ability to have an anonymous sender or receiver. |
---|
| 17 | Additionally all channel operations in CSP are synchronous (no buffering). |
---|
| 18 | Advanced channels as a programming language feature has been popularized in recent years by the language Go~\cite{Go}, which encourages the use of channels as its fundamental concurrent feature. |
---|
[44198fb9] | 19 | It was the popularity of Go channels that lead to their implementation in \CFA. |
---|
[76e77a4] | 20 | Neither Go nor \CFA channels have the restrictions of the early channel-based concurrent systems. |
---|
[5fd5de2] | 21 | |
---|
[9509d67a] | 22 | Other popular languages and libraries that provide channels include C++ Boost~\cite{boost:channel}, Rust~\cite{rust:channel}, Haskell~\cite{haskell:channel}, OCaml~\cite{ocaml:channel}, and Kotlin~\cite{kotlin:channel}. |
---|
[ac5d22f] | 23 | Boost channels only support asynchronous (non-blocking) operations, and Rust channels are limited to only having one consumer per channel. |
---|
| 24 | Haskell channels are unbounded in size, and OCaml channels are zero-size. |
---|
| 25 | These restrictions in Haskell and OCaml are likely due to their functional approach, which results in them both using a list as the underlying data structure for their channel. |
---|
| 26 | These languages and libraries are not discussed further, as their channel implementation is not comparable to the bounded-buffer style channels present in Go and \CFA. |
---|
[9509d67a] | 27 | Kotlin channels are comparable to Go and \CFA, but unfortunately they were not identified as a comparator until after presentation of this thesis and are omitted due to time constraints. |
---|
[ac5d22f] | 28 | |
---|
[5fd5de2] | 29 | \section{Producer-Consumer Problem} |
---|
[e9fffb1] | 30 | A channel is an abstraction for a shared-memory buffer, which turns the implementation of a channel into the producer-consumer problem. |
---|
| 31 | The producer-consumer problem, also known as the bounded-buffer problem, was introduced by Dijkstra~\cite[\S~4.1]{Dijkstra65}. |
---|
| 32 | In the problem, threads interact with a buffer in two ways: producing threads insert values into the buffer and consuming threads remove values from the buffer. |
---|
| 33 | In general, a buffer needs protection to ensure a producer only inserts into a non-full buffer and a consumer only removes from a non-empty buffer (synchronization). |
---|
[9509d67a] | 34 | As well, a buffer needs protection from concurrent access by multiple producers or consumers attempting to insert or remove simultaneously, which is often provided by MX. |
---|
[e9fffb1] | 35 | |
---|
[9f1beb4] | 36 | \section{Channel Size}\label{s:ChannelSize} |
---|
[e9fffb1] | 37 | Channels come in three flavours of buffers: |
---|
| 38 | \begin{enumerate} |
---|
| 39 | \item |
---|
| 40 | Zero sized implies the communication is synchronous, \ie the producer must wait for the consumer to arrive or vice versa for a value to be communicated. |
---|
| 41 | \item |
---|
[aae9c17] | 42 | Fixed sized (bounded) implies the communication is mostly asynchronous, \ie the producer can proceed up to the buffer size and vice versa for the consumer with respect to removal, at which point the producer/consumer would wait. |
---|
[e9fffb1] | 43 | \item |
---|
[9509d67a] | 44 | Infinite sized (unbounded) implies the communication is asymmetrically asynchronous, \ie the producer never waits but the consumer waits when the buffer is empty. |
---|
[e9fffb1] | 45 | \end{enumerate} |
---|
| 46 | |
---|
[ca8c91ce] | 47 | In general, the order values are processed by the consumer does not affect the correctness of the producer-consumer problem. |
---|
[5384793] | 48 | For example, the buffer can be \gls{lifo}, \gls{fifo}, or prioritized with respect to insertion and removal. |
---|
[e9fffb1] | 49 | However, like MX, a buffer should ensure every value is eventually removed after some reasonable bounded time (no long-term starvation). |
---|
| 50 | The simplest way to prevent starvation is to implement the buffer as a queue, either with a cyclic array or linked nodes. |
---|
[9509d67a] | 51 | While \gls{fifo} is not required for producer-consumer problem correctness, it is a desired property in channels as it provides predictable and often relied upon channel ordering behaviour to users. |
---|
[5fd5de2] | 52 | |
---|
| 53 | \section{First-Come First-Served} |
---|
[9509d67a] | 54 | As pointed out, a bounded buffer implementation often provides MX among multiple producers or consumers. |
---|
[5384793] | 55 | This MX should be fair among threads, independent of the \gls{fifo} buffer being fair among values. |
---|
[e9fffb1] | 56 | Fairness among threads is called \gls{fcfs} and was defined by Lamport~\cite[p.~454]{Lamport74}. |
---|
[3d5fba21] | 57 | \gls{fcfs} is defined in relation to a doorway~\cite[p.~330]{Lamport86II}, which is the point at which an ordering among threads can be established. |
---|
[ca8c91ce] | 58 | Given this doorway, a CS is said to be \gls{fcfs}, if threads access the shared resource in the order they proceed through the doorway. |
---|
| 59 | A consequence of \gls{fcfs} execution is the elimination of \Newterm{barging}, where barging means a thread arrives at a CS with waiting threads, and the MX protecting the CS allows the arriving thread to enter the CS ahead of one or more of the waiting threads. |
---|
[e9fffb1] | 60 | |
---|
[ca8c91ce] | 61 | \gls{fcfs} is a fairness property that prevents unequal access to the shared resource and prevents starvation, however it comes at a cost. |
---|
[9f1beb4] | 62 | Implementing an algorithm with \gls{fcfs} can lead to \Newterm{double blocking}, where arriving threads block outside the doorway waiting for a thread in the lock entry-protocol and inside the doorway waiting for a thread in the CS. |
---|
[ca8c91ce] | 63 | An analogue is boarding an airplane: first you wait to get through security to the departure gates (short term), and then wait again at the departure gate for the airplane (long term). |
---|
| 64 | As such, algorithms that are not \gls{fcfs} (barging) can be more performant by skipping the wait for the CS and entering directly; |
---|
| 65 | however, this performance gain comes by introducing unfairness with possible starvation for waiting threads. |
---|
[5fd5de2] | 66 | |
---|
[5e6fb07] | 67 | \section{Channel Implementation}\label{s:chan_impl} |
---|
[9509d67a] | 68 | The programming languages Go, Kotlin, and Erlang provide user-level threading where the primary communication mechanism is channels. |
---|
| 69 | These languages have user-level threading and preemptive scheduling, and both use channels for communication. |
---|
| 70 | Go and Kotlin provide multiple homogeneous channels; each have a single associated type. |
---|
[aae9c17] | 71 | Erlang, which is closely related to actor systems, provides one heterogeneous channel per thread (mailbox) with a typed receive pattern. |
---|
[9509d67a] | 72 | Go and Kotlin encourage users to communicate via channels, but provides them as an optional language feature. |
---|
[aae9c17] | 73 | On the other hand, Erlang's single heterogeneous channel is a fundamental part of the threading system design; using it is unavoidable. |
---|
[9509d67a] | 74 | Similar to Go and Kotlin, \CFA's channels are offered as an optional language feature. |
---|
[aae9c17] | 75 | |
---|
| 76 | While iterating on channel implementation, experiments were conducted that varied the producer-consumer algorithm and lock type used inside the channel. |
---|
[5384793] | 77 | With the exception of non-\gls{fcfs} or non-\gls{fifo} algorithms, no algorithm or lock usage in the channel implementation was found to be consistently more performant that Go's choice of algorithm and lock implementation. |
---|
[76e77a4] | 78 | Performance of channels can be improved by sharding the underlying buffer \cite{Dice11}. |
---|
[5384793] | 79 | However, the \gls{fifo} property is lost, which is undesirable for user-facing channels. |
---|
[ca8c91ce] | 80 | Therefore, the low-level channel implementation in \CFA is largely copied from the Go implementation, but adapted to the \CFA type and runtime systems. |
---|
[9a5a2cd] | 81 | As such the research contributions added by \CFA's channel implementation lie in the realm of safety and productivity features. |
---|
[5fd5de2] | 82 | |
---|
[44198fb9] | 83 | The Go channel implementation utilizes cooperation among threads to achieve good performance~\cite{go:chan}. |
---|
| 84 | This cooperation only occurs when producers or consumers need to block due to the buffer being full or empty. |
---|
[9509d67a] | 85 | After a producer blocks it must wait for a consumer to signal it and vice versa. |
---|
| 86 | The consumer or producer that signals a blocked thread is called the signalling thread. |
---|
[44198fb9] | 87 | In these cases, a blocking thread stores their relevant data in a shared location and the signalling thread completes the blocking thread's operation before waking them; |
---|
| 88 | \ie the blocking thread has no work to perform after it unblocks because the signalling threads has done this work. |
---|
| 89 | This approach is similar to wait morphing for locks~\cite[p.~82]{Butenhof97} and improves performance in a few ways. |
---|
| 90 | First, each thread interacting with the channel only acquires and releases the internal channel lock once. |
---|
[0ec4eb0] | 91 | As a result, contention on the internal lock is decreased; only entering threads compete for the lock since unblocking threads do not reacquire the lock. |
---|
[9509d67a] | 92 | The other advantage of Go's wait-morphing approach is that it eliminates the need to wait for signalled threads to run. |
---|
[aae9c17] | 93 | Note that the property of acquiring/releasing the lock only once can also be achieved with a different form of cooperation, called \Newterm{baton passing}. |
---|
[44198fb9] | 94 | Baton passing occurs when one thread acquires a lock but does not release it, and instead signals a thread inside the critical section, conceptually ``passing'' the mutual exclusion from the signalling thread to the signalled thread. |
---|
| 95 | The baton-passing approach has threads cooperate to pass mutual exclusion without additional lock acquires or releases; |
---|
| 96 | the wait-morphing approach has threads cooperate by completing the signalled thread's operation, thus removing a signalled thread's need for mutual exclusion after unblocking. |
---|
| 97 | While baton passing is useful in some algorithms, it results in worse channel performance than the Go approach. |
---|
[9509d67a] | 98 | In the baton-passing approach, all threads need to wait for the signalled thread to unblock and run before other operations on the channel can proceed, since the signalled thread holds mutual exclusion; |
---|
[44198fb9] | 99 | in the wait-morphing approach, since the operation is completed before the signal, other threads can continue to operate on the channel without waiting for the signalled thread to run. |
---|
[2d831a1] | 100 | |
---|
[9f1beb4] | 101 | In this work, all channel sizes \see{Sections~\ref{s:ChannelSize}} are implemented with bounded buffers. |
---|
| 102 | However, only non-zero-sized buffers are analysed because of their complexity and higher usage. |
---|
[ca8c91ce] | 103 | |
---|
[6e83384] | 104 | \section{Safety and Productivity} |
---|
[3d5fba21] | 105 | Channels in \CFA come with safety and productivity features to aid users. |
---|
[9a5a2cd] | 106 | The features include the following. |
---|
[5fd5de2] | 107 | |
---|
[6e83384] | 108 | \begin{itemize} |
---|
[ca8c91ce] | 109 | \item Toggle-able statistic collection on channel behaviour that count channel and blocking operations. |
---|
[9f1beb4] | 110 | Tracking blocking operations helps illustrate usage for tuning the channel size, where the aim is to reduce blocking. |
---|
| 111 | |
---|
| 112 | \item Deadlock detection on channel deallocation. |
---|
| 113 | If threads are blocked inside a channel when it terminates, this case is detected and the user is informed, as this can cause a deadlock. |
---|
| 114 | |
---|
[ca8c91ce] | 115 | \item A @flush@ routine that delivers copies of an element to all waiting consumers, flushing the buffer. |
---|
[9f1beb4] | 116 | Programmers use this mechanism to broadcast a sentinel value to multiple consumers. |
---|
[000d68f] | 117 | Additionally, the @flush@ routine is more performant than looping around the @insert@ operation since it can deliver the elements without having to reacquire mutual exclusion for each element sent. |
---|
[e0396d9] | 118 | |
---|
[daf4c89] | 119 | \item Go-style @?<<?@ shorthand operator for inserting and removing. |
---|
[e0396d9] | 120 | \begin{cfa} |
---|
| 121 | channel(int) chan; |
---|
| 122 | int i = 2; |
---|
[daf4c89] | 123 | chan << i; $\C{// insert i into chan}$ |
---|
[e0396d9] | 124 | i << chan; $\C{// remove element from chan into i}$ |
---|
| 125 | \end{cfa} |
---|
[6e83384] | 126 | \end{itemize} |
---|
[5fd5de2] | 127 | |
---|
[9f1beb4] | 128 | \subsection{Toggle-able Statistics} |
---|
[76e77a4] | 129 | As discussed, a channel is a concurrent layer over a bounded buffer. |
---|
[44198fb9] | 130 | To achieve efficient buffering, users should aim for as few blocking operations on a channel as possible. |
---|
| 131 | Mechanisms to reduce blocking are: change the buffer size, shard a channel into multiple channels, or tweak the number of producer and consumer threads. |
---|
| 132 | For users to be able to make informed decisions when tuning channel usage, toggle-able channel statistics are provided. |
---|
| 133 | The statistics are toggled on during the \CFA build by defining the @CHAN_STATS@ macro, which guarantees zero cost when not using this feature. |
---|
| 134 | When statistics are turned on, four counters are maintained per channel, two for inserting (producers) and two for removing (consumers). |
---|
[76e77a4] | 135 | The two counters per type of operation track the number of blocking operations and total operations. |
---|
[44198fb9] | 136 | In the channel destructor, the counters are printed out aggregated and also per type of operation. |
---|
| 137 | An example use case is noting that producer inserts are blocking often while consumer removes do not block often. |
---|
| 138 | This information can be used to increase the number of consumers to decrease the blocking producer operations, thus increasing the channel throughput. |
---|
| 139 | Whereas, increasing the channel size in this scenario is unlikely to produce a benefit because the consumers can never keep up with the producers. |
---|
[9f1beb4] | 140 | |
---|
| 141 | \subsection{Deadlock Detection} |
---|
[44198fb9] | 142 | The deadlock detection in the \CFA channels is fairly basic but detects a very common channel mistake during termination. |
---|
| 143 | That is, it detects the case where threads are blocked on the channel during channel deallocation. |
---|
[e4a2198] | 144 | This case is guaranteed to deadlock since there are no other threads to supply or consume values needed by the waiting threads. |
---|
| 145 | Only if a user maintained a separate reference to the blocked threads and manually unblocks them outside the channel could the deadlock be avoid. |
---|
| 146 | However, without special semantics, this unblocking would generate other runtime errors where the unblocked thread attempts to access non-existing channel data or even a deallocated channel. |
---|
[44198fb9] | 147 | More robust deadlock detection needs to be implemented separate from channels since it requires knowledge about the threading system and other channel/thread state. |
---|
[9f1beb4] | 148 | |
---|
| 149 | \subsection{Program Shutdown} |
---|
[3d5fba21] | 150 | Terminating concurrent programs is often one of the most difficult parts of writing concurrent code, particularly if graceful termination is needed. |
---|
[e4a2198] | 151 | Graceful termination can be difficult to achieve with synchronization primitives that need to be handled carefully during shutdown. |
---|
[3d5fba21] | 152 | It is easy to deadlock during termination if threads are left behind on synchronization primitives. |
---|
| 153 | Additionally, most synchronization primitives are prone to \gls{toctou} issues where there is race between one thread checking the state of a concurrent object and another thread changing the state. |
---|
| 154 | \gls{toctou} issues with synchronization primitives often involve a race between one thread checking the primitive for blocked threads and another thread blocking on it. |
---|
[9f1beb4] | 155 | Channels are a particularly hard synchronization primitive to terminate since both sending and receiving to/from a channel can block. |
---|
[44198fb9] | 156 | Thus, improperly handled \gls{toctou} issues with channels often result in deadlocks as threads performing the termination may end up unexpectedly blocking in their attempt to help other threads exit the system. |
---|
[5fd5de2] | 157 | |
---|
[3ee8853] | 158 | \subsubsection{Go Channel Close} |
---|
[aae9c17] | 159 | Go channels provide a set of tools to help with concurrent shutdown~\cite{go:chan} using a @close@ operation in conjunction with the \Go{select} statement. |
---|
[76e77a4] | 160 | The \Go{select} statement is discussed in \ref{s:waituntil}, where \CFA's @waituntil@ statement is compared with the Go \Go{select} statement. |
---|
[9f1beb4] | 161 | |
---|
[ca8c91ce] | 162 | The @close@ operation on a channel in Go changes the state of the channel. |
---|
[9f1beb4] | 163 | When a channel is closed, sends to the channel panic along with additional calls to @close@. |
---|
[76e77a4] | 164 | Receives are handled differently. |
---|
| 165 | Receivers (consumers) never block on a closed channel and continue to remove elements from the channel. |
---|
[9f1beb4] | 166 | Once a channel is empty, receivers can continue to remove elements, but receive the zero-value version of the element type. |
---|
| 167 | To avoid unwanted zero-value elements, Go provides the ability to iterate over a closed channel to remove the remaining elements. |
---|
| 168 | These Go design choices enforce a specific interaction style with channels during termination: careful thought is needed to ensure additional @close@ calls do not occur and no sends occur after a channel is closed. |
---|
[3d5fba21] | 169 | These design choices fit Go's paradigm of error management, where users are expected to explicitly check for errors, rather than letting errors occur and catching them. |
---|
[9f1beb4] | 170 | If errors need to occur in Go, return codes are used to pass error information up call levels. |
---|
[aae9c17] | 171 | Note that panics in Go can be caught, but it is not the idiomatic way to write Go programs. |
---|
[9a5a2cd] | 172 | |
---|
[44198fb9] | 173 | While Go's channel-closing semantics are powerful enough to perform any concurrent termination needed by a program, their lack of ease of use leaves much to be desired. |
---|
[76e77a4] | 174 | Since both closing and sending panic once a channel is closed, a user often has to synchronize the senders (producers) before the channel can be closed to avoid panics. |
---|
[9f1beb4] | 175 | However, in doing so it renders the @close@ operation nearly useless, as the only utilities it provides are the ability to ensure receivers no longer block on the channel and receive zero-valued elements. |
---|
| 176 | This functionality is only useful if the zero-typed element is recognized as a sentinel value, but if another sentinel value is necessary, then @close@ only provides the non-blocking feature. |
---|
[ca8c91ce] | 177 | To avoid \gls{toctou} issues during shutdown, a busy wait with a \Go{select} statement is often used to add or remove elements from a channel. |
---|
[44198fb9] | 178 | Hence, due to Go's asymmetric approach to channel shutdown, separate synchronization between producers and consumers of a channel has to occur during shutdown. |
---|
[5fd5de2] | 179 | |
---|
[3ee8853] | 180 | \subsubsection{\CFA Channel Close} |
---|
| 181 | \CFA channels have access to an extensive exception handling mechanism~\cite{Beach21}. |
---|
[9f1beb4] | 182 | As such \CFA uses an exception-based approach to channel shutdown that is symmetric for both producers and consumers, and supports graceful shutdown. |
---|
| 183 | |
---|
| 184 | Exceptions in \CFA support both termination and resumption. |
---|
| 185 | \Newterm{Termination exception}s perform a dynamic call that unwinds the stack preventing the exception handler from returning to the raise point, such as in \CC, Python and Java. |
---|
| 186 | \Newterm{Resumption exception}s perform a dynamic call that does not unwind the stack allowing the exception handler to return to the raise point. |
---|
| 187 | In \CFA, if a resumption exception is not handled, it is reraised as a termination exception. |
---|
| 188 | This mechanism is used to create a flexible and robust termination system for channels. |
---|
| 189 | |
---|
| 190 | When a channel in \CFA is closed, all subsequent calls to the channel raise a resumption exception at the caller. |
---|
| 191 | If the resumption is handled, the caller attempts to complete the channel operation. |
---|
[44198fb9] | 192 | However, if the channel operation would block, a termination exception is thrown. |
---|
[9f1beb4] | 193 | If the resumption is not handled, the exception is rethrown as a termination. |
---|
| 194 | These termination exceptions allow for non-local transfer that is used to great effect to eagerly and gracefully shut down a thread. |
---|
[3d5fba21] | 195 | When a channel is closed, if there are any blocked producers or consumers inside the channel, they are woken up and also have a resumption thrown at them. |
---|
[44198fb9] | 196 | The resumption exception, @channel_closed@, has internal fields to aid in handling the exception. |
---|
| 197 | The exception contains a pointer to the channel it is thrown from and a pointer to a buffer element. |
---|
| 198 | For exceptions thrown from @remove@, the buffer element pointer is null. |
---|
| 199 | For exceptions thrown from @insert@, the element pointer points to the buffer element that the thread attempted to insert. |
---|
[e4a2198] | 200 | Utility routines @bool is_insert( channel_closed & e );@ and @bool is_remove( channel_closed & e );@ are provided for convenient checking of the element pointer. |
---|
[3d5fba21] | 201 | This element pointer allows the handler to know which operation failed and also allows the element to not be lost on a failed insert since it can be moved elsewhere in the handler. |
---|
[44198fb9] | 202 | Furthermore, due to \CFA's powerful exception system, this data can be used to choose handlers based on which channel and operation failed. |
---|
| 203 | For example, exception handlers in \CFA have an optional predicate which can be used to trigger or skip handlers based on the content of the matching exception. |
---|
| 204 | It is worth mentioning that using exceptions for termination may incur a larger performance cost than the Go approach. |
---|
| 205 | However, this should not be an issue, since termination is rarely on the fast-path of an application. |
---|
| 206 | In contrast, ensuring termination can be easily implemented correctly is the aim of the exception approach. |
---|
[9a5a2cd] | 207 | |
---|
[9f1beb4] | 208 | \section{\CFA / Go channel Examples} |
---|
[56eb7f8] | 209 | To highlight the differences between \CFA's and Go's close semantics, two examples are presented. |
---|
[76e77a4] | 210 | The first example is a simple shutdown case, where there are producer threads and consumer threads operating on a channel for a fixed duration. |
---|
[44198fb9] | 211 | Once the duration ends, producers and consumers terminate immediately leaving unprocessed elements in the channel. |
---|
| 212 | The second example extends the first by requiring the channel to be empty after shutdown. |
---|
[76e77a4] | 213 | Both the first and second example are shown in Figure~\ref{f:ChannelTermination}. |
---|
| 214 | |
---|
| 215 | \begin{figure} |
---|
| 216 | \centering |
---|
| 217 | |
---|
| 218 | \begin{lrbox}{\myboxA} |
---|
[44198fb9] | 219 | \begin{Golang}[aboveskip=0pt,belowskip=0pt] |
---|
| 220 | var channel chan int = make( chan int, 128 ) |
---|
| 221 | var prodJoin chan int = make( chan int, 4 ) |
---|
| 222 | var consJoin chan int = make( chan int, 4 ) |
---|
| 223 | var cons_done, prod_done bool = false, false; |
---|
| 224 | func producer() { |
---|
| 225 | for { |
---|
| 226 | if prod_done { break } |
---|
| 227 | channel <- 5 |
---|
| 228 | } |
---|
| 229 | prodJoin <- 0 // synch with main thd |
---|
[76e77a4] | 230 | } |
---|
| 231 | |
---|
[44198fb9] | 232 | func consumer() { |
---|
| 233 | for { |
---|
| 234 | if cons_done { break } |
---|
| 235 | <- channel |
---|
| 236 | } |
---|
| 237 | consJoin <- 0 // synch with main thd |
---|
[76e77a4] | 238 | } |
---|
| 239 | |
---|
[44198fb9] | 240 | |
---|
| 241 | func main() { |
---|
| 242 | for j := 0; j < 4; j++ { go consumer() } |
---|
| 243 | for j := 0; j < 4; j++ { go producer() } |
---|
| 244 | time.Sleep( time.Second * 10 ) |
---|
| 245 | prod_done = true |
---|
| 246 | for j := 0; j < 4 ; j++ { <- prodJoin } |
---|
| 247 | cons_done = true |
---|
| 248 | close(channel) // ensure no cons deadlock |
---|
| 249 | @for elem := range channel {@ |
---|
| 250 | // process leftover values |
---|
| 251 | @}@ |
---|
| 252 | for j := 0; j < 4; j++ { <- consJoin } |
---|
[76e77a4] | 253 | } |
---|
[44198fb9] | 254 | \end{Golang} |
---|
[76e77a4] | 255 | \end{lrbox} |
---|
| 256 | |
---|
| 257 | \begin{lrbox}{\myboxB} |
---|
| 258 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
[c03c1ac] | 259 | channel( int ) chan{ 128 }; |
---|
[44198fb9] | 260 | thread Consumer {}; |
---|
| 261 | thread Producer {}; |
---|
[76e77a4] | 262 | |
---|
[44198fb9] | 263 | void main( Producer & this ) { |
---|
| 264 | try { |
---|
| 265 | for () |
---|
[c03c1ac] | 266 | chan << 5; |
---|
[44198fb9] | 267 | } catch( channel_closed * ) { |
---|
| 268 | // unhandled resume or full |
---|
| 269 | } |
---|
[76e77a4] | 270 | } |
---|
[44198fb9] | 271 | void main( Consumer & this ) { |
---|
[c03c1ac] | 272 | int i; |
---|
[44198fb9] | 273 | try { |
---|
[c03c1ac] | 274 | for () { i << chan; } |
---|
[44198fb9] | 275 | @} catchResume( channel_closed * ) {@ |
---|
| 276 | // handled resume => consume from chan |
---|
| 277 | } catch( channel_closed * ) { |
---|
| 278 | // empty or unhandled resume |
---|
| 279 | } |
---|
| 280 | } |
---|
| 281 | int main() { |
---|
| 282 | Consumer c[4]; |
---|
| 283 | Producer p[4]; |
---|
| 284 | sleep( 10`s ); |
---|
| 285 | close( chan ); |
---|
[76e77a4] | 286 | } |
---|
[44198fb9] | 287 | |
---|
| 288 | |
---|
| 289 | |
---|
| 290 | |
---|
| 291 | |
---|
| 292 | |
---|
[76e77a4] | 293 | \end{cfa} |
---|
| 294 | \end{lrbox} |
---|
| 295 | |
---|
[44198fb9] | 296 | \subfloat[Go style]{\label{l:go_chan_term}\usebox\myboxA} |
---|
[76e77a4] | 297 | \hspace*{3pt} |
---|
| 298 | \vrule |
---|
| 299 | \hspace*{3pt} |
---|
[44198fb9] | 300 | \subfloat[\CFA style]{\label{l:cfa_chan_term}\usebox\myboxB} |
---|
[76e77a4] | 301 | \caption{Channel Termination Examples 1 and 2. Code specific to example 2 is highlighted.} |
---|
| 302 | \label{f:ChannelTermination} |
---|
| 303 | \end{figure} |
---|
| 304 | |
---|
[44198fb9] | 305 | Figure~\ref{l:go_chan_term} shows the Go solution. |
---|
| 306 | Since some of the elements being passed through the channel are zero-valued, closing the channel in Go does not aid in communicating shutdown. |
---|
| 307 | Instead, a different mechanism to communicate with the consumers and producers needs to be used. |
---|
| 308 | Flag variables are common in Go-channel shutdown-code to avoid panics on a channel, meaning the channel shutdown has to be communicated with threads before it occurs. |
---|
| 309 | Hence, the two flags @cons_done@ and @prod_done@ are used to communicate with the producers and consumers, respectively. |
---|
[e4a2198] | 310 | Furthermore, producers and consumers need to shutdown separately to ensure that producers terminate before the channel is closed to avoid panicking, and to avoid the case where all the consumers terminate first, which can result in a deadlock for producers if the channel is full. |
---|
[44198fb9] | 311 | The producer flag is set first; |
---|
| 312 | then after all producers terminate, the consumer flag is set and the channel is closed leaving elements in the buffer. |
---|
| 313 | To purge the buffer, a loop is added (red) that iterates over the closed channel to process any remaining values. |
---|
| 314 | |
---|
| 315 | Figure~\ref{l:cfa_chan_term} shows the \CFA solution. |
---|
| 316 | Here, shutdown is communicated directly to both producers and consumers via the @close@ call. |
---|
| 317 | A @Producer@ thread knows to stop producing when the @insert@ call on a closed channel raises exception @channel_closed@. |
---|
| 318 | If a @Consumer@ thread ignores the first resumption exception from the @close@, the exception is reraised as a termination exception and elements are left in the buffer. |
---|
| 319 | If a @Consumer@ thread handles the resumptions exceptions (red), control returns to complete the remove. |
---|
| 320 | A @Consumer@ thread knows to stop consuming after all elements of a closed channel are removed and the consumer would block, which causes a termination raise of @channel_closed@. |
---|
| 321 | The \CFA semantics allow users to communicate channel shutdown directly through the channel, without having to share extra state between threads. |
---|
| 322 | Additionally, when the channel needs to be drained, \CFA provides users with easy options for processing the leftover channel values in the main thread or in the consumer threads. |
---|
[76e77a4] | 323 | |
---|
[44198fb9] | 324 | Figure~\ref{f:ChannelBarrierTermination} shows a final shutdown example using channels to implement a barrier. |
---|
| 325 | A Go and \CFA style solution are presented but both are implemented using \CFA syntax so they can be easily compared. |
---|
| 326 | Implementing a barrier is interesting because threads are both producers and consumers on the barrier-internal channels, @entryWait@ and @barWait@. |
---|
| 327 | The outline for the barrier implementation starts by initially filling the @entryWait@ channel with $N$ tickets in the barrier constructor, allowing $N$ arriving threads to remove these values and enter the barrier. |
---|
[5d81edb] | 328 | After @entryWait@ is empty, arriving threads block when removing. |
---|
[44198fb9] | 329 | However, the arriving threads that entered the barrier cannot leave the barrier until $N$ threads have arrived. |
---|
[5d81edb] | 330 | Hence, the entering threads block on the empty @barWait@ channel until the $N$th arriving thread inserts $N-1$ elements into @barWait@ to unblock the $N-1$ threads calling @remove@. |
---|
[44198fb9] | 331 | The race between these arriving threads blocking on @barWait@ and the $N$th thread inserting values into @barWait@ does not affect correctness; |
---|
| 332 | \ie an arriving thread may or may not block on channel @barWait@ to get its value. |
---|
[5d81edb] | 333 | Finally, the last thread to remove from @barWait@ with ticket $N-2$, refills channel @entryWait@ with $N$ values to start the next group into the barrier. |
---|
[44198fb9] | 334 | |
---|
| 335 | Now, the two channels makes termination synchronization between producers and consumers difficult. |
---|
| 336 | Interestingly, the shutdown details for this problem are also applicable to other problems with threads producing and consuming from the same channel. |
---|
| 337 | The Go-style solution cannot use the Go @close@ call since all threads are both potentially producers and consumers, causing panics on close to be unavoidable without complex synchronization. |
---|
| 338 | As such in Figure \ref{l:go_chan_bar}, a flush routine is needed to insert a sentinel value, @-1@, to inform threads waiting in the buffer they need to leave the barrier. |
---|
| 339 | This sentinel value has to be checked at two points along the fast-path and sentinel values daisy-chained into the buffers. |
---|
| 340 | Furthermore, an additional flag @done@ is needed to communicate to threads once they have left the barrier that they are done. |
---|
[9a5a2cd] | 341 | Also note that in the Go version~\ref{l:go_chan_bar}, the size of the barrier channels has to be larger than in the \CFA version to ensure that the main thread does not block when attempting to clear the barrier. |
---|
[44198fb9] | 342 | For The \CFA solution~\ref{l:cfa_chan_bar}, the barrier shutdown results in an exception being thrown at threads operating on it, to inform waiting threads they must leave the barrier. |
---|
| 343 | This avoids the need to use a separate communication method other than the barrier, and avoids extra conditional checks on the fast path of the barrier implementation. |
---|
[5fd5de2] | 344 | |
---|
[9f1beb4] | 345 | \begin{figure} |
---|
| 346 | \centering |
---|
| 347 | |
---|
| 348 | \begin{lrbox}{\myboxA} |
---|
| 349 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
[6e83384] | 350 | struct barrier { |
---|
[9f1beb4] | 351 | channel( int ) barWait, entryWait; |
---|
[3d5fba21] | 352 | int size; |
---|
[9f1beb4] | 353 | }; |
---|
| 354 | void ?{}( barrier & this, int size ) with(this) { |
---|
[44198fb9] | 355 | barWait{size + 1}; entryWait{size + 1}; |
---|
[3d5fba21] | 356 | this.size = size; |
---|
[9f1beb4] | 357 | for ( i; size ) |
---|
| 358 | insert( entryWait, i ); |
---|
[6e83384] | 359 | } |
---|
[9f1beb4] | 360 | void wait( barrier & this ) with(this) { |
---|
| 361 | int ticket = remove( entryWait ); |
---|
[44198fb9] | 362 | @if ( ticket == -1 ) { insert( entryWait, -1 ); return; }@ |
---|
[3d5fba21] | 363 | if ( ticket == size - 1 ) { |
---|
[9f1beb4] | 364 | for ( i; size - 1 ) |
---|
| 365 | insert( barWait, i ); |
---|
[3d5fba21] | 366 | return; |
---|
| 367 | } |
---|
[9f1beb4] | 368 | ticket = remove( barWait ); |
---|
[44198fb9] | 369 | @if ( ticket == -1 ) { insert( barWait, -1 ); return; }@ |
---|
[9f1beb4] | 370 | if ( size == 1 || ticket == size - 2 ) { // last ? |
---|
| 371 | for ( i; size ) |
---|
| 372 | insert( entryWait, i ); |
---|
[3d5fba21] | 373 | } |
---|
[6e83384] | 374 | } |
---|
[9f1beb4] | 375 | void flush(barrier & this) with(this) { |
---|
[44198fb9] | 376 | @insert( entryWait, -1 ); insert( barWait, -1 );@ |
---|
[9f1beb4] | 377 | } |
---|
| 378 | enum { Threads = 4 }; |
---|
| 379 | barrier b{Threads}; |
---|
[44198fb9] | 380 | @bool done = false;@ |
---|
[9f1beb4] | 381 | thread Thread {}; |
---|
| 382 | void main( Thread & this ) { |
---|
[44198fb9] | 383 | for () { |
---|
| 384 | @if ( done ) break;@ |
---|
| 385 | wait( b ); |
---|
| 386 | } |
---|
[6e83384] | 387 | } |
---|
| 388 | int main() { |
---|
[9f1beb4] | 389 | Thread t[Threads]; |
---|
| 390 | sleep(10`s); |
---|
[44198fb9] | 391 | done = true; |
---|
[9f1beb4] | 392 | flush( b ); |
---|
| 393 | } // wait for threads to terminate |
---|
[9363b1b] | 394 | \end{cfa} |
---|
[9f1beb4] | 395 | \end{lrbox} |
---|
[6e83384] | 396 | |
---|
[9f1beb4] | 397 | \begin{lrbox}{\myboxB} |
---|
| 398 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
[6e83384] | 399 | struct barrier { |
---|
[9f1beb4] | 400 | channel( int ) barWait, entryWait; |
---|
[3d5fba21] | 401 | int size; |
---|
[9f1beb4] | 402 | }; |
---|
| 403 | void ?{}( barrier & this, int size ) with(this) { |
---|
[44198fb9] | 404 | barWait{size}; entryWait{size}; |
---|
[3d5fba21] | 405 | this.size = size; |
---|
[9f1beb4] | 406 | for ( i; size ) |
---|
| 407 | insert( entryWait, i ); |
---|
[6e83384] | 408 | } |
---|
[9f1beb4] | 409 | void wait( barrier & this ) with(this) { |
---|
| 410 | int ticket = remove( entryWait ); |
---|
[44198fb9] | 411 | |
---|
[3d5fba21] | 412 | if ( ticket == size - 1 ) { |
---|
[9f1beb4] | 413 | for ( i; size - 1 ) |
---|
| 414 | insert( barWait, i ); |
---|
[3d5fba21] | 415 | return; |
---|
| 416 | } |
---|
[9f1beb4] | 417 | ticket = remove( barWait ); |
---|
[44198fb9] | 418 | |
---|
[9f1beb4] | 419 | if ( size == 1 || ticket == size - 2 ) { // last ? |
---|
| 420 | for ( i; size ) |
---|
| 421 | insert( entryWait, i ); |
---|
[3d5fba21] | 422 | } |
---|
[6e83384] | 423 | } |
---|
[9f1beb4] | 424 | void flush(barrier & this) with(this) { |
---|
[44198fb9] | 425 | @close( barWait ); close( entryWait );@ |
---|
[9f1beb4] | 426 | } |
---|
| 427 | enum { Threads = 4 }; |
---|
| 428 | barrier b{Threads}; |
---|
[44198fb9] | 429 | |
---|
[9f1beb4] | 430 | thread Thread {}; |
---|
| 431 | void main( Thread & this ) { |
---|
[44198fb9] | 432 | @try {@ |
---|
| 433 | for () |
---|
| 434 | wait( b ); |
---|
| 435 | @} catch ( channel_closed * ) {}@ |
---|
[6e83384] | 436 | } |
---|
| 437 | int main() { |
---|
[9f1beb4] | 438 | Thread t[Threads]; |
---|
| 439 | sleep(10`s); |
---|
[44198fb9] | 440 | |
---|
[9f1beb4] | 441 | flush( b ); |
---|
| 442 | } // wait for threads to terminate |
---|
[9363b1b] | 443 | \end{cfa} |
---|
[9f1beb4] | 444 | \end{lrbox} |
---|
| 445 | |
---|
[44198fb9] | 446 | \subfloat[Go style]{\label{l:go_chan_bar}\usebox\myboxA} |
---|
[9f1beb4] | 447 | \hspace*{3pt} |
---|
| 448 | \vrule |
---|
| 449 | \hspace*{3pt} |
---|
[44198fb9] | 450 | \subfloat[\CFA style]{\label{l:cfa_chan_bar}\usebox\myboxB} |
---|
[9f1beb4] | 451 | \caption{Channel Barrier Termination} |
---|
| 452 | \label{f:ChannelBarrierTermination} |
---|
| 453 | \end{figure} |
---|
[5fd5de2] | 454 | |
---|
| 455 | \section{Performance} |
---|
[6e83384] | 456 | |
---|
[9f1beb4] | 457 | Given that the base implementation of the \CFA channels is very similar to the Go implementation, this section aims to show the performance of the two implementations are comparable. |
---|
[76e77a4] | 458 | The microbenchmark for the channel comparison is similar to Figure~\ref{f:ChannelTermination}, where the number of threads and processors is set from the command line. |
---|
[9f1beb4] | 459 | The processors are divided equally between producers and consumers, with one producer or consumer owning each core. |
---|
[9921573] | 460 | The number of cores is varied to measure how throughput scales. |
---|
[9f1beb4] | 461 | |
---|
[3d5fba21] | 462 | The results of the benchmark are shown in Figure~\ref{f:chanPerf}. |
---|
| 463 | The performance of Go and \CFA channels on this microbenchmark is comparable. |
---|
[aae9c17] | 464 | Note that the performance should decline as the number of cores increases as the channel operations occur in a critical section, so increasing cores results in higher contention with no increase in parallelism. |
---|
| 465 | |
---|
| 466 | The performance of \CFA and Go's shutdown mechanisms is not measured, as shutdown is an exceptional case that does not occur frequently in most programs. Additionally, it is difficult to measure channel shutdown performance; threads need to be synchronized between each subsequent shutdown, which is likely more expensive than the shutdown mechanism itself. |
---|
[6e83384] | 467 | |
---|
| 468 | \begin{figure} |
---|
[3d5fba21] | 469 | \centering |
---|
[aae9c17] | 470 | \subfloat[AMD Channel Benchmark]{ |
---|
[3d5fba21] | 471 | \resizebox{0.5\textwidth}{!}{\input{figures/nasus_Channel_Contention.pgf}} |
---|
| 472 | \label{f:chanAMD} |
---|
| 473 | } |
---|
[aae9c17] | 474 | \subfloat[Intel Channel Benchmark]{ |
---|
[3d5fba21] | 475 | \resizebox{0.5\textwidth}{!}{\input{figures/pyke_Channel_Contention.pgf}} |
---|
| 476 | \label{f:chanIntel} |
---|
| 477 | } |
---|
| 478 | \caption{The channel contention benchmark comparing \CFA and Go channel throughput (higher is better).} |
---|
| 479 | \label{f:chanPerf} |
---|
[6e83384] | 480 | \end{figure} |
---|
[3d5fba21] | 481 | |
---|
| 482 | % Local Variables: % |
---|
| 483 | % tab-width: 4 % |
---|
| 484 | % End: % |
---|