1 | % ====================================================================== |
---|
2 | % ====================================================================== |
---|
3 | \chapter{Channels}\label{s:channels} |
---|
4 | % ====================================================================== |
---|
5 | % ====================================================================== |
---|
6 | |
---|
7 | Most modern concurrent programming languages do not subscribe to just one style of communication among threads and provide features that support multiple approaches. |
---|
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). |
---|
9 | This model is an alternative to shared-memory concurrency, where threads communicate directly by changing shared state. |
---|
10 | |
---|
11 | Channels were first introduced by Kahn~\cite{Kahn74} and extended by Hoare~\cite{CSP} (CSP). |
---|
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. |
---|
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. |
---|
19 | It was the popularity of Go channels that lead to their implementation in \CFA. |
---|
20 | Neither Go nor \CFA channels have the restrictions of the early channel-based concurrent systems. |
---|
21 | |
---|
22 | Other popular languages and libraries that provide channels include C++ Boost~\cite{boost:channel}, Rust~\cite{rust:channel}, Haskell~\cite{haskell:channel}, and OCaml~\cite{ocaml:channel}. |
---|
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. |
---|
27 | |
---|
28 | \section{Producer-Consumer Problem} |
---|
29 | A channel is an abstraction for a shared-memory buffer, which turns the implementation of a channel into the producer-consumer problem. |
---|
30 | The producer-consumer problem, also known as the bounded-buffer problem, was introduced by Dijkstra~\cite[\S~4.1]{Dijkstra65}. |
---|
31 | 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. |
---|
32 | 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). |
---|
33 | As well, a buffer needs protection from concurrent access by multiple producers or consumers attempting to insert or remove simultaneously (MX). |
---|
34 | |
---|
35 | \section{Channel Size}\label{s:ChannelSize} |
---|
36 | Channels come in three flavours of buffers: |
---|
37 | \begin{enumerate} |
---|
38 | \item |
---|
39 | 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. |
---|
40 | \item |
---|
41 | 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. |
---|
42 | \item |
---|
43 | Infinite sized (unbounded) implies the communication is asynchronous, \ie the producer never waits but the consumer waits when the buffer is empty. |
---|
44 | Since memory is finite, all unbounded buffers are ultimately bounded; |
---|
45 | this restriction must be part of its implementation. |
---|
46 | \end{enumerate} |
---|
47 | |
---|
48 | In general, the order values are processed by the consumer does not affect the correctness of the producer-consumer problem. |
---|
49 | For example, the buffer can be \gls{lifo}, \gls{fifo}, or prioritized with respect to insertion and removal. |
---|
50 | However, like MX, a buffer should ensure every value is eventually removed after some reasonable bounded time (no long-term starvation). |
---|
51 | The simplest way to prevent starvation is to implement the buffer as a queue, either with a cyclic array or linked nodes. |
---|
52 | |
---|
53 | \section{First-Come First-Served} |
---|
54 | As pointed out, a bounded buffer requires MX among multiple producers or consumers. |
---|
55 | This MX should be fair among threads, independent of the \gls{fifo} buffer being fair among values. |
---|
56 | Fairness among threads is called \gls{fcfs} and was defined by Lamport~\cite[p.~454]{Lamport74}. |
---|
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. |
---|
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. |
---|
60 | |
---|
61 | \gls{fcfs} is a fairness property that prevents unequal access to the shared resource and prevents starvation, however it comes at a cost. |
---|
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. |
---|
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. |
---|
66 | |
---|
67 | \section{Channel Implementation}\label{s:chan_impl} |
---|
68 | Currently, only the Go and Erlang programming languages provide user-level threading where the primary communication mechanism is channels. |
---|
69 | Both Go and Erlang have user-level threading and preemptive scheduling, and both use channels for communication. |
---|
70 | Go provides multiple homogeneous channels; each have a single associated type. |
---|
71 | Erlang, which is closely related to actor systems, provides one heterogeneous channel per thread (mailbox) with a typed receive pattern. |
---|
72 | Go encourages users to communicate via channels, but provides them as an optional language feature. |
---|
73 | On the other hand, Erlang's single heterogeneous channel is a fundamental part of the threading system design; using it is unavoidable. |
---|
74 | Similar to Go, \CFA's channels are offered as an optional language feature. |
---|
75 | |
---|
76 | While iterating on channel implementation, experiments were conducted that varied the producer-consumer algorithm and lock type used inside the channel. |
---|
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. |
---|
78 | Performance of channels can be improved by sharding the underlying buffer \cite{Dice11}. |
---|
79 | However, the \gls{fifo} property is lost, which is undesirable for user-facing channels. |
---|
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. |
---|
81 | As such the research contributions added by \CFA's channel implementation lie in the realm of safety and productivity features. |
---|
82 | |
---|
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. |
---|
85 | 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; |
---|
86 | \ie the blocking thread has no work to perform after it unblocks because the signalling threads has done this work. |
---|
87 | This approach is similar to wait morphing for locks~\cite[p.~82]{Butenhof97} and improves performance in a few ways. |
---|
88 | First, each thread interacting with the channel only acquires and releases the internal channel lock once. |
---|
89 | 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. |
---|
90 | The other advantage of Go's wait-morphing approach is that it eliminates the bottleneck of waiting for signalled threads to run. |
---|
91 | 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}. |
---|
92 | 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. |
---|
93 | The baton-passing approach has threads cooperate to pass mutual exclusion without additional lock acquires or releases; |
---|
94 | 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. |
---|
95 | While baton passing is useful in some algorithms, it results in worse channel performance than the Go approach. |
---|
96 | In the baton-passing approach, all threads need to wait for the signalled thread to reach the front of the ready queue, context switch, and run before other operations on the channel can proceed, since the signalled thread holds mutual exclusion; |
---|
97 | 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. |
---|
98 | |
---|
99 | In this work, all channel sizes \see{Sections~\ref{s:ChannelSize}} are implemented with bounded buffers. |
---|
100 | However, only non-zero-sized buffers are analysed because of their complexity and higher usage. |
---|
101 | |
---|
102 | \section{Safety and Productivity} |
---|
103 | Channels in \CFA come with safety and productivity features to aid users. |
---|
104 | The features include the following. |
---|
105 | |
---|
106 | \begin{itemize} |
---|
107 | \item Toggle-able statistic collection on channel behaviour that count channel and blocking operations. |
---|
108 | Tracking blocking operations helps illustrate usage for tuning the channel size, where the aim is to reduce blocking. |
---|
109 | |
---|
110 | \item Deadlock detection on channel deallocation. |
---|
111 | 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. |
---|
112 | |
---|
113 | \item A @flush@ routine that delivers copies of an element to all waiting consumers, flushing the buffer. |
---|
114 | Programmers use this mechanism to broadcast a sentinel value to multiple consumers. |
---|
115 | 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. |
---|
116 | |
---|
117 | \item Go-style @?<<?@ shorthand operator for inserting and removing. |
---|
118 | \begin{cfa} |
---|
119 | channel(int) chan; |
---|
120 | int i = 2; |
---|
121 | chan << i; $\C{// insert i into chan}$ |
---|
122 | i << chan; $\C{// remove element from chan into i}$ |
---|
123 | \end{cfa} |
---|
124 | \end{itemize} |
---|
125 | |
---|
126 | \subsection{Toggle-able Statistics} |
---|
127 | As discussed, a channel is a concurrent layer over a bounded buffer. |
---|
128 | To achieve efficient buffering, users should aim for as few blocking operations on a channel as possible. |
---|
129 | Mechanisms to reduce blocking are: change the buffer size, shard a channel into multiple channels, or tweak the number of producer and consumer threads. |
---|
130 | For users to be able to make informed decisions when tuning channel usage, toggle-able channel statistics are provided. |
---|
131 | The statistics are toggled on during the \CFA build by defining the @CHAN_STATS@ macro, which guarantees zero cost when not using this feature. |
---|
132 | When statistics are turned on, four counters are maintained per channel, two for inserting (producers) and two for removing (consumers). |
---|
133 | The two counters per type of operation track the number of blocking operations and total operations. |
---|
134 | In the channel destructor, the counters are printed out aggregated and also per type of operation. |
---|
135 | An example use case is noting that producer inserts are blocking often while consumer removes do not block often. |
---|
136 | This information can be used to increase the number of consumers to decrease the blocking producer operations, thus increasing the channel throughput. |
---|
137 | Whereas, increasing the channel size in this scenario is unlikely to produce a benefit because the consumers can never keep up with the producers. |
---|
138 | |
---|
139 | \subsection{Deadlock Detection} |
---|
140 | The deadlock detection in the \CFA channels is fairly basic but detects a very common channel mistake during termination. |
---|
141 | That is, it detects the case where threads are blocked on the channel during channel deallocation. |
---|
142 | This case is guaranteed to deadlock since there are no other threads to supply or consume values needed by the waiting threads. |
---|
143 | Only if a user maintained a separate reference to the blocked threads and manually unblocks them outside the channel could the deadlock be avoid. |
---|
144 | 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. |
---|
145 | More robust deadlock detection needs to be implemented separate from channels since it requires knowledge about the threading system and other channel/thread state. |
---|
146 | |
---|
147 | \subsection{Program Shutdown} |
---|
148 | Terminating concurrent programs is often one of the most difficult parts of writing concurrent code, particularly if graceful termination is needed. |
---|
149 | Graceful termination can be difficult to achieve with synchronization primitives that need to be handled carefully during shutdown. |
---|
150 | It is easy to deadlock during termination if threads are left behind on synchronization primitives. |
---|
151 | 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. |
---|
152 | \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. |
---|
153 | Channels are a particularly hard synchronization primitive to terminate since both sending and receiving to/from a channel can block. |
---|
154 | 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. |
---|
155 | |
---|
156 | \subsubsection{Go Channel Close} |
---|
157 | 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. |
---|
158 | The \Go{select} statement is discussed in \ref{s:waituntil}, where \CFA's @waituntil@ statement is compared with the Go \Go{select} statement. |
---|
159 | |
---|
160 | The @close@ operation on a channel in Go changes the state of the channel. |
---|
161 | When a channel is closed, sends to the channel panic along with additional calls to @close@. |
---|
162 | Receives are handled differently. |
---|
163 | Receivers (consumers) never block on a closed channel and continue to remove elements from the channel. |
---|
164 | Once a channel is empty, receivers can continue to remove elements, but receive the zero-value version of the element type. |
---|
165 | To avoid unwanted zero-value elements, Go provides the ability to iterate over a closed channel to remove the remaining elements. |
---|
166 | 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. |
---|
167 | 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. |
---|
168 | If errors need to occur in Go, return codes are used to pass error information up call levels. |
---|
169 | Note that panics in Go can be caught, but it is not the idiomatic way to write Go programs. |
---|
170 | |
---|
171 | 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. |
---|
172 | 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. |
---|
173 | 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. |
---|
174 | 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. |
---|
175 | 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. |
---|
176 | Hence, due to Go's asymmetric approach to channel shutdown, separate synchronization between producers and consumers of a channel has to occur during shutdown. |
---|
177 | |
---|
178 | \subsubsection{\CFA Channel Close} |
---|
179 | \CFA channels have access to an extensive exception handling mechanism~\cite{Beach21}. |
---|
180 | As such \CFA uses an exception-based approach to channel shutdown that is symmetric for both producers and consumers, and supports graceful shutdown. |
---|
181 | |
---|
182 | Exceptions in \CFA support both termination and resumption. |
---|
183 | \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. |
---|
184 | \Newterm{Resumption exception}s perform a dynamic call that does not unwind the stack allowing the exception handler to return to the raise point. |
---|
185 | In \CFA, if a resumption exception is not handled, it is reraised as a termination exception. |
---|
186 | This mechanism is used to create a flexible and robust termination system for channels. |
---|
187 | |
---|
188 | When a channel in \CFA is closed, all subsequent calls to the channel raise a resumption exception at the caller. |
---|
189 | If the resumption is handled, the caller attempts to complete the channel operation. |
---|
190 | However, if the channel operation would block, a termination exception is thrown. |
---|
191 | If the resumption is not handled, the exception is rethrown as a termination. |
---|
192 | These termination exceptions allow for non-local transfer that is used to great effect to eagerly and gracefully shut down a thread. |
---|
193 | 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. |
---|
194 | The resumption exception, @channel_closed@, has internal fields to aid in handling the exception. |
---|
195 | The exception contains a pointer to the channel it is thrown from and a pointer to a buffer element. |
---|
196 | For exceptions thrown from @remove@, the buffer element pointer is null. |
---|
197 | For exceptions thrown from @insert@, the element pointer points to the buffer element that the thread attempted to insert. |
---|
198 | Utility routines @bool is_insert( channel_closed & e );@ and @bool is_remove( channel_closed & e );@ are provided for convenient checking of the element pointer. |
---|
199 | 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. |
---|
200 | Furthermore, due to \CFA's powerful exception system, this data can be used to choose handlers based on which channel and operation failed. |
---|
201 | 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. |
---|
202 | It is worth mentioning that using exceptions for termination may incur a larger performance cost than the Go approach. |
---|
203 | However, this should not be an issue, since termination is rarely on the fast-path of an application. |
---|
204 | In contrast, ensuring termination can be easily implemented correctly is the aim of the exception approach. |
---|
205 | |
---|
206 | \section{\CFA / Go channel Examples} |
---|
207 | To highlight the differences between \CFA's and Go's close semantics, two examples are presented. |
---|
208 | The first example is a simple shutdown case, where there are producer threads and consumer threads operating on a channel for a fixed duration. |
---|
209 | Once the duration ends, producers and consumers terminate immediately leaving unprocessed elements in the channel. |
---|
210 | The second example extends the first by requiring the channel to be empty after shutdown. |
---|
211 | Both the first and second example are shown in Figure~\ref{f:ChannelTermination}. |
---|
212 | |
---|
213 | \begin{figure} |
---|
214 | \centering |
---|
215 | |
---|
216 | \begin{lrbox}{\myboxA} |
---|
217 | \begin{Golang}[aboveskip=0pt,belowskip=0pt] |
---|
218 | var channel chan int = make( chan int, 128 ) |
---|
219 | var prodJoin chan int = make( chan int, 4 ) |
---|
220 | var consJoin chan int = make( chan int, 4 ) |
---|
221 | var cons_done, prod_done bool = false, false; |
---|
222 | func producer() { |
---|
223 | for { |
---|
224 | if prod_done { break } |
---|
225 | channel <- 5 |
---|
226 | } |
---|
227 | prodJoin <- 0 // synch with main thd |
---|
228 | } |
---|
229 | |
---|
230 | func consumer() { |
---|
231 | for { |
---|
232 | if cons_done { break } |
---|
233 | <- channel |
---|
234 | } |
---|
235 | consJoin <- 0 // synch with main thd |
---|
236 | } |
---|
237 | |
---|
238 | |
---|
239 | func main() { |
---|
240 | for j := 0; j < 4; j++ { go consumer() } |
---|
241 | for j := 0; j < 4; j++ { go producer() } |
---|
242 | time.Sleep( time.Second * 10 ) |
---|
243 | prod_done = true |
---|
244 | for j := 0; j < 4 ; j++ { <- prodJoin } |
---|
245 | cons_done = true |
---|
246 | close(channel) // ensure no cons deadlock |
---|
247 | @for elem := range channel {@ |
---|
248 | // process leftover values |
---|
249 | @}@ |
---|
250 | for j := 0; j < 4; j++ { <- consJoin } |
---|
251 | } |
---|
252 | \end{Golang} |
---|
253 | \end{lrbox} |
---|
254 | |
---|
255 | \begin{lrbox}{\myboxB} |
---|
256 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
257 | channel( int ) chan{ 128 }; |
---|
258 | thread Consumer {}; |
---|
259 | thread Producer {}; |
---|
260 | |
---|
261 | void main( Producer & this ) { |
---|
262 | try { |
---|
263 | for () |
---|
264 | chan << 5; |
---|
265 | } catch( channel_closed * ) { |
---|
266 | // unhandled resume or full |
---|
267 | } |
---|
268 | } |
---|
269 | void main( Consumer & this ) { |
---|
270 | int i; |
---|
271 | try { |
---|
272 | for () { i << chan; } |
---|
273 | @} catchResume( channel_closed * ) {@ |
---|
274 | // handled resume => consume from chan |
---|
275 | } catch( channel_closed * ) { |
---|
276 | // empty or unhandled resume |
---|
277 | } |
---|
278 | } |
---|
279 | int main() { |
---|
280 | Consumer c[4]; |
---|
281 | Producer p[4]; |
---|
282 | sleep( 10`s ); |
---|
283 | close( chan ); |
---|
284 | } |
---|
285 | |
---|
286 | |
---|
287 | |
---|
288 | |
---|
289 | |
---|
290 | |
---|
291 | \end{cfa} |
---|
292 | \end{lrbox} |
---|
293 | |
---|
294 | \subfloat[Go style]{\label{l:go_chan_term}\usebox\myboxA} |
---|
295 | \hspace*{3pt} |
---|
296 | \vrule |
---|
297 | \hspace*{3pt} |
---|
298 | \subfloat[\CFA style]{\label{l:cfa_chan_term}\usebox\myboxB} |
---|
299 | \caption{Channel Termination Examples 1 and 2. Code specific to example 2 is highlighted.} |
---|
300 | \label{f:ChannelTermination} |
---|
301 | \end{figure} |
---|
302 | |
---|
303 | Figure~\ref{l:go_chan_term} shows the Go solution. |
---|
304 | Since some of the elements being passed through the channel are zero-valued, closing the channel in Go does not aid in communicating shutdown. |
---|
305 | Instead, a different mechanism to communicate with the consumers and producers needs to be used. |
---|
306 | 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. |
---|
307 | Hence, the two flags @cons_done@ and @prod_done@ are used to communicate with the producers and consumers, respectively. |
---|
308 | 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. |
---|
309 | The producer flag is set first; |
---|
310 | then after all producers terminate, the consumer flag is set and the channel is closed leaving elements in the buffer. |
---|
311 | To purge the buffer, a loop is added (red) that iterates over the closed channel to process any remaining values. |
---|
312 | |
---|
313 | Figure~\ref{l:cfa_chan_term} shows the \CFA solution. |
---|
314 | Here, shutdown is communicated directly to both producers and consumers via the @close@ call. |
---|
315 | A @Producer@ thread knows to stop producing when the @insert@ call on a closed channel raises exception @channel_closed@. |
---|
316 | 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. |
---|
317 | If a @Consumer@ thread handles the resumptions exceptions (red), control returns to complete the remove. |
---|
318 | 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@. |
---|
319 | The \CFA semantics allow users to communicate channel shutdown directly through the channel, without having to share extra state between threads. |
---|
320 | 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. |
---|
321 | |
---|
322 | Figure~\ref{f:ChannelBarrierTermination} shows a final shutdown example using channels to implement a barrier. |
---|
323 | A Go and \CFA style solution are presented but both are implemented using \CFA syntax so they can be easily compared. |
---|
324 | Implementing a barrier is interesting because threads are both producers and consumers on the barrier-internal channels, @entryWait@ and @barWait@. |
---|
325 | 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. |
---|
326 | After @entryWait@ is empty, arriving threads block when removing. |
---|
327 | However, the arriving threads that entered the barrier cannot leave the barrier until $N$ threads have arrived. |
---|
328 | 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@. |
---|
329 | The race between these arriving threads blocking on @barWait@ and the $N$th thread inserting values into @barWait@ does not affect correctness; |
---|
330 | \ie an arriving thread may or may not block on channel @barWait@ to get its value. |
---|
331 | 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. |
---|
332 | |
---|
333 | Now, the two channels makes termination synchronization between producers and consumers difficult. |
---|
334 | Interestingly, the shutdown details for this problem are also applicable to other problems with threads producing and consuming from the same channel. |
---|
335 | 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. |
---|
336 | 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. |
---|
337 | This sentinel value has to be checked at two points along the fast-path and sentinel values daisy-chained into the buffers. |
---|
338 | Furthermore, an additional flag @done@ is needed to communicate to threads once they have left the barrier that they are done. |
---|
339 | 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. |
---|
340 | 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. |
---|
341 | 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. |
---|
342 | |
---|
343 | \begin{figure} |
---|
344 | \centering |
---|
345 | |
---|
346 | \begin{lrbox}{\myboxA} |
---|
347 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
348 | struct barrier { |
---|
349 | channel( int ) barWait, entryWait; |
---|
350 | int size; |
---|
351 | }; |
---|
352 | void ?{}( barrier & this, int size ) with(this) { |
---|
353 | barWait{size + 1}; entryWait{size + 1}; |
---|
354 | this.size = size; |
---|
355 | for ( i; size ) |
---|
356 | insert( entryWait, i ); |
---|
357 | } |
---|
358 | void wait( barrier & this ) with(this) { |
---|
359 | int ticket = remove( entryWait ); |
---|
360 | @if ( ticket == -1 ) { insert( entryWait, -1 ); return; }@ |
---|
361 | if ( ticket == size - 1 ) { |
---|
362 | for ( i; size - 1 ) |
---|
363 | insert( barWait, i ); |
---|
364 | return; |
---|
365 | } |
---|
366 | ticket = remove( barWait ); |
---|
367 | @if ( ticket == -1 ) { insert( barWait, -1 ); return; }@ |
---|
368 | if ( size == 1 || ticket == size - 2 ) { // last ? |
---|
369 | for ( i; size ) |
---|
370 | insert( entryWait, i ); |
---|
371 | } |
---|
372 | } |
---|
373 | void flush(barrier & this) with(this) { |
---|
374 | @insert( entryWait, -1 ); insert( barWait, -1 );@ |
---|
375 | } |
---|
376 | enum { Threads = 4 }; |
---|
377 | barrier b{Threads}; |
---|
378 | @bool done = false;@ |
---|
379 | thread Thread {}; |
---|
380 | void main( Thread & this ) { |
---|
381 | for () { |
---|
382 | @if ( done ) break;@ |
---|
383 | wait( b ); |
---|
384 | } |
---|
385 | } |
---|
386 | int main() { |
---|
387 | Thread t[Threads]; |
---|
388 | sleep(10`s); |
---|
389 | done = true; |
---|
390 | flush( b ); |
---|
391 | } // wait for threads to terminate |
---|
392 | \end{cfa} |
---|
393 | \end{lrbox} |
---|
394 | |
---|
395 | \begin{lrbox}{\myboxB} |
---|
396 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
397 | struct barrier { |
---|
398 | channel( int ) barWait, entryWait; |
---|
399 | int size; |
---|
400 | }; |
---|
401 | void ?{}( barrier & this, int size ) with(this) { |
---|
402 | barWait{size}; entryWait{size}; |
---|
403 | this.size = size; |
---|
404 | for ( i; size ) |
---|
405 | insert( entryWait, i ); |
---|
406 | } |
---|
407 | void wait( barrier & this ) with(this) { |
---|
408 | int ticket = remove( entryWait ); |
---|
409 | |
---|
410 | if ( ticket == size - 1 ) { |
---|
411 | for ( i; size - 1 ) |
---|
412 | insert( barWait, i ); |
---|
413 | return; |
---|
414 | } |
---|
415 | ticket = remove( barWait ); |
---|
416 | |
---|
417 | if ( size == 1 || ticket == size - 2 ) { // last ? |
---|
418 | for ( i; size ) |
---|
419 | insert( entryWait, i ); |
---|
420 | } |
---|
421 | } |
---|
422 | void flush(barrier & this) with(this) { |
---|
423 | @close( barWait ); close( entryWait );@ |
---|
424 | } |
---|
425 | enum { Threads = 4 }; |
---|
426 | barrier b{Threads}; |
---|
427 | |
---|
428 | thread Thread {}; |
---|
429 | void main( Thread & this ) { |
---|
430 | @try {@ |
---|
431 | for () |
---|
432 | wait( b ); |
---|
433 | @} catch ( channel_closed * ) {}@ |
---|
434 | } |
---|
435 | int main() { |
---|
436 | Thread t[Threads]; |
---|
437 | sleep(10`s); |
---|
438 | |
---|
439 | flush( b ); |
---|
440 | } // wait for threads to terminate |
---|
441 | \end{cfa} |
---|
442 | \end{lrbox} |
---|
443 | |
---|
444 | \subfloat[Go style]{\label{l:go_chan_bar}\usebox\myboxA} |
---|
445 | \hspace*{3pt} |
---|
446 | \vrule |
---|
447 | \hspace*{3pt} |
---|
448 | \subfloat[\CFA style]{\label{l:cfa_chan_bar}\usebox\myboxB} |
---|
449 | \caption{Channel Barrier Termination} |
---|
450 | \label{f:ChannelBarrierTermination} |
---|
451 | \end{figure} |
---|
452 | |
---|
453 | \section{Performance} |
---|
454 | |
---|
455 | 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. |
---|
456 | 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. |
---|
457 | The processors are divided equally between producers and consumers, with one producer or consumer owning each core. |
---|
458 | The number of cores is varied to measure how throughput scales. |
---|
459 | |
---|
460 | The results of the benchmark are shown in Figure~\ref{f:chanPerf}. |
---|
461 | The performance of Go and \CFA channels on this microbenchmark is comparable. |
---|
462 | 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. |
---|
463 | |
---|
464 | 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. |
---|
465 | |
---|
466 | \begin{figure} |
---|
467 | \centering |
---|
468 | \subfloat[AMD Channel Benchmark]{ |
---|
469 | \resizebox{0.5\textwidth}{!}{\input{figures/nasus_Channel_Contention.pgf}} |
---|
470 | \label{f:chanAMD} |
---|
471 | } |
---|
472 | \subfloat[Intel Channel Benchmark]{ |
---|
473 | \resizebox{0.5\textwidth}{!}{\input{figures/pyke_Channel_Contention.pgf}} |
---|
474 | \label{f:chanIntel} |
---|
475 | } |
---|
476 | \caption{The channel contention benchmark comparing \CFA and Go channel throughput (higher is better).} |
---|
477 | \label{f:chanPerf} |
---|
478 | \end{figure} |
---|
479 | |
---|
480 | % Local Variables: % |
---|
481 | % tab-width: 4 % |
---|
482 | % End: % |
---|