source: doc/theses/colby_parsons_MMAth/text/channels.tex @ 4912520

ADTast-experimental
Last change on this file since 4912520 was ca8c91ce, checked in by Peter A. Buhr <pabuhr@…>, 14 months ago

small changes to channel chapter

  • Property mode set to 100644
File size: 20.3 KB
Line 
1% ======================================================================
2% ======================================================================
3\chapter{Channels}\label{s:channels}
4% ======================================================================
5% ======================================================================
6
7Most modern concurrent programming languages do not subscribe to just one style of communication among threads and provide features that support multiple approaches.
8Channels 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).
9This model is an alternative to shared-memory concurrency, where threads can communicate directly by changing shared state.
10
11Channels were first introduced by Kahn~\cite{Kahn74} and extended by Hoare~\cite{Hoare78} (CSP).
12Both papers present a pseudo (unimplemented) concurrent language where processes communicate using input/output channels to send data.
13Both languages are highly restrictive.
14Kahn'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.
15Hoare's language restricts ...
16Channels as a programming language feature has been popularized in recent years by the language Go, which encourages the use of channels as its fundamental concurrent feature.
17Go's restrictions are ...
18\CFA channels do not have these restrictions.
19
20\section{Producer-Consumer Problem}
21A channel is an abstraction for a shared-memory buffer, which turns the implementation of a channel into the producer-consumer problem.
22The producer-consumer problem, also known as the bounded-buffer problem, was introduced by Dijkstra~\cite[\S~4.1]{Dijkstra65}.
23In 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.
24In 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).
25As well, a buffer needs protection at each end resulting from concurrent access by multiple producers or consumers attempt to insert or remove simultaneously (MX).
26
27Channels come in three flavours of buffers:
28\begin{enumerate}
29\item
30Zero 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.
31\item
32Fixed sized (bounded) implies the communication is asynchronous, \ie the producer can proceed up to the buffer size and vice versa for the consumer with respect to removal.
33\item
34Infinite sized (unbounded) implies the communication is asynchronous, \ie the producer never waits but the consumer waits when the buffer is empty.
35Since memory is finite, all unbounded buffers are ultimately bounded;
36this restrict must be part of its implementation.
37\end{enumerate}
38
39In general, the order values are processed by the consumer does not affect the correctness of the producer-consumer problem.
40For example, the buffer can be LIFO, FIFO, or prioritized with respect to insertion and removal.
41However, like MX, a buffer should ensure every value is eventually removed after some reasonable bounded time (no long-term starvation).
42The simplest way to prevent starvation is to implement the buffer as a queue, either with a cyclic array or linked nodes.
43
44\section{First-Come First-Served}
45As pointed out, a bounded buffer requires MX among multiple producers or consumers at either end of the buffer.
46This MX should be fair among threads, independent of the FIFO buffer being fair among values.
47Fairness among threads is called \gls{fcfs} and was defined by Lamport~\cite[p.~454]{Lamport74}.
48\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.
49Given this doorway, a CS is said to be \gls{fcfs}, if threads access the shared resource in the order they proceed through the doorway.
50A 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.
51
52\gls{fcfs} is a fairness property that prevents unequal access to the shared resource and prevents starvation, however it comes at a cost.
53Implementing an algorithm with \gls{fcfs} can lead to 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.
54An 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).
55As such, algorithms that are not \gls{fcfs} (barging) can be more performant by skipping the wait for the CS and entering directly;
56however, this performance gain comes by introducing unfairness with possible starvation for waiting threads.
57
58\section{Channel Implementation}
59Currently, only the Go programming language~\cite{Go} provides user-level threading where the primary communication mechanism is channels.
60Experiments were conducted that varied the producer-consumer problem algorithm and lock type used inside the channel.
61With the exception of non-\gls{fcfs} 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.
62Therefore, the low-level channel implementation in \CFA is largely copied from the Go implementation, but adapted to the \CFA type and runtime systems.
63As such the research contributions added by \CFA's channel implementation lie in the realm of safety and productivity features.
64
65\PAB{Discuss the Go channel implementation. Need to tie in FIFO buffer and FCFS locking.}
66In this work, all channels are implemented with bounded buffers, so there is no zero-sized buffering.
67
68\section{Safety and Productivity}
69Channels in \CFA come with safety and productivity features to aid users.
70The features include the following.
71
72\begin{itemize}
73\item Toggle-able statistic collection on channel behaviour that count channel and blocking operations.
74Tracking blocking operations helps illustrate usage and then tune the channel size, where the aim is to reduce blocking.
75\item Deadlock detection on deallocation of the channel.
76If threads are blocked inside the channel when it terminates, this case is detected and the user is informed, as this can cause a deadlock.
77\item A @flush@ routine that delivers copies of an element to all waiting consumers, flushing the buffer.
78Programmers can use this to easily to broadcast data to multiple consumers.
79Additionally, the @flush@ routine is more performant then looping around the @insert@ operation since it can deliver the elements without having to reacquire mutual exclusion for each element sent.
80\end{itemize}
81
82The other safety and productivity feature of \CFA channels deals with concurrent termination.
83Terminating concurrent programs is often one of the most difficult parts of writing concurrent code, particularly if graceful termination is needed.
84The difficulty of graceful termination often arises from the usage of synchronization primitives which need to be handled carefully during shutdown.
85It is easy to deadlock during termination if threads are left behind on synchronization primitives.
86Additionally, 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.
87\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.
88Channels are a particularly hard synchronization primitive to terminate since both sending and receiving off a channel can block.
89Thus, improperly handled \gls{toctou} issues with channels often result in deadlocks as threads trying to perform the termination may end up unexpectedly blocking in their attempt to help other threads exit the system.
90
91% C_TODO: add reference to select chapter, add citation to go channels info
92Go channels provide a set of tools to help with concurrent shutdown.
93Channels in Go have a @close@ operation and a \Go{select} statement that both can be used to help threads terminate.
94The \Go{select} statement will be discussed in \ref{}, where \CFA's @waituntil@ statement will be compared with the Go \Go{select} statement.
95The @close@ operation on a channel in Go changes the state of the channel.
96When a channel is closed, sends to the channel will panic and additional calls to @close@ will panic.
97Receives are handled differently where receivers will never block on a closed channel and will continue to remove elements from the channel.
98Once a channel is empty, receivers can continue to remove elements, but will receive the zero-value version of the element type.
99To aid in avoiding unwanted zero-value elements, Go provides the ability to iterate over a closed channel to remove the remaining elements.
100These design choices for Go channels enforce a specific interaction style with channels during termination, where careful thought is needed to ensure that additional @close@ calls don't occur and that no sends occur after channels are closed.
101These 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.
102If errors need to occur in Go, return codes are used to pass error information where they are needed.
103Note that panics in Go can be caught, but it is not considered an idiomatic way to write Go programs.
104
105While 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.
106Since both closing and sending panic, once a channel is closed, a user often has to synchronize the senders to a channel before the channel can be closed to avoid panics.
107However, in doing so it renders the @close@ operation nearly useless, as the only utilities it provides are the ability to ensure that receivers no longer block on the channel, and will receive zero-valued elements.
108This can be useful if the zero-typed element is recognized as a sentinel value, but if another sentinel value is preferred, then @close@ only provides its non-blocking feature.
109To 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.
110Due to Go's asymmetric approach to channel shutdown, separate synchronization between producers and consumers of a channel has to occur during shutdown.
111
112In \CFA, exception handling is an encouraged paradigm and has full language support \cite{Beach21}.
113As such \CFA uses an exception based approach to channel shutdown that is symmetric for both producers and consumers, and supports graceful shutdown.Exceptions in \CFA support both termination and resumption.Termination exceptions operate in the same way as exceptions seen in many popular programming languages such as \CC, Python and Java.
114Resumption exceptions are a style of exception that when caught run the corresponding catch block in the same way that termination exceptions do.
115The difference between the exception handling mechanisms arises after the exception is handled.
116In termination handling, the control flow continues into the code following the catch after the exception is handled.
117In resumption handling, the control flow returns to the site of the @throw@, allowing the control to continue where it left off.
118Note that in resumption, since control can return to the point of error propagation, the stack is not unwound during resumption propagation.
119In \CFA if a resumption is not handled, it is reraised as a termination.
120This mechanism can be used to create a flexible and robust termination system for channels.
121
122When a channel in \CFA is closed, all subsequent calls to the channel will throw a resumption exception at the caller.
123If the resumption is handled, then the caller will proceed to attempt to complete their operation.
124If the resumption is not handled it is then rethrown as a termination exception.
125Or, if the resumption is handled, but the subsequent attempt at an operation would block, a termination exception is thrown.
126These termination exceptions allow for non-local transfer that can be used to great effect to eagerly and gracefully shut down a thread.
127When 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.
128The resumption exception, @channel_closed@, has a couple fields to aid in handling the exception.
129The exception contains a pointer to the channel it was thrown from, and a pointer to an element.
130In exceptions thrown from remove the element pointer will be null.
131In the case of insert the element pointer points to the element that the thread attempted to insert.
132This 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.
133Furthermore, due to \CFA's powerful exception system, this data can be used to choose handlers based which channel and operation failed.
134Exception handlers in \CFA have an optional predicate after the exception type which can be used to optionally trigger or skip handlers based on the content of an exception.
135It is worth mentioning that the approach of exceptions for termination may incur a larger performance cost during termination that the approach used in Go.
136This should not be an issue, since termination is rarely an fast-path of an application and ensuring that termination can be implemented correctly with ease is the aim of the exception approach.
137
138To highlight the differences between \CFA's and Go's close semantics, an example program is presented.
139The program is a barrier implemented using two channels shown in Listings~\ref{l:cfa_chan_bar} and \ref{l:go_chan_bar}.
140Both of these examples are implemented using \CFA syntax so that they can be easily compared.
141Listing~\ref{l:go_chan_bar} uses go-style channel close semantics and Listing~\ref{l:cfa_chan_bar} uses \CFA close semantics.
142In this problem it is infeasible to use the Go @close@ call since all tasks are both potentially producers and consumers, causing panics on close to be unavoidable.
143As such in Listing~\ref{l:go_chan_bar} to implement a flush routine for the buffer, a sentinel value of $-1$ has to be used to indicate to threads that they need to leave the barrier.
144This sentinel value has to be checked at two points.
145Furthermore, an additional flag @done@ is needed to communicate to threads once they have left the barrier that they are done.
146This use of an additional flag or communication method is common in Go channel shutdown code, since to avoid panics on a channel, the shutdown of a channel often has to be communicated with threads before it occurs.
147In the \CFA version~\ref{l:cfa_chan_bar}, the barrier shutdown results in an exception being thrown at threads operating on it, which informs the threads that they must terminate.
148This 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.
149Also 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.
150
151\begin{cfa}[caption={\CFA channel barrier termination},label={l:cfa_chan_bar}]
152struct barrier {
153        channel( int ) barWait;
154        channel( int ) entryWait;
155        int size;
156}
157void ?{}(barrier & this, int size) with(this) {
158        barWait{size};
159        entryWait{size};
160        this.size = size;
161        for ( j; size )
162                insert( *entryWait, j );
163}
164
165void flush(barrier & this) with(this) {
166        close(barWait);
167        close(entryWait);
168}
169void wait(barrier & this) with(this) {
170        int ticket = remove( *entryWait );
171        if ( ticket == size - 1 ) {
172                for ( j; size - 1 )
173                        insert( *barWait, j );
174                return;
175        }
176        ticket = remove( *barWait );
177
178        // last one out
179        if ( size == 1 || ticket == size - 2 ) {
180                for ( j; size )
181                        insert( *entryWait, j );
182        }
183}
184barrier b{Tasks};
185
186// thread main
187void main(Task & this) {
188        try {
189                for ( ;; ) {
190                        wait( b );
191                }
192        } catch ( channel_closed * e ) {}
193}
194
195int main() {
196        {
197                Task t[Tasks];
198
199                sleep(10`s);
200                flush( b );
201        } // wait for tasks to terminate
202        return 0;
203}
204\end{cfa}
205
206\begin{cfa}[caption={Go channel barrier termination},label={l:go_chan_bar}]
207
208struct barrier {
209        channel( int ) barWait;
210        channel( int ) entryWait;
211        int size;
212}
213void ?{}(barrier & this, int size) with(this) {
214        barWait{size + 1};
215        entryWait{size + 1};
216        this.size = size;
217        for ( j; size )
218                insert( *entryWait, j );
219}
220
221void flush(barrier & this) with(this) {
222        insert( *entryWait, -1 );
223        insert( *barWait, -1 );
224}
225void wait(barrier & this) with(this) {
226        int ticket = remove( *entryWait );
227        if ( ticket == -1 ) {
228                insert( *entryWait, -1 );
229                return;
230        }
231        if ( ticket == size - 1 ) {
232                for ( j; size - 1 )
233                        insert( *barWait, j );
234                return;
235        }
236        ticket = remove( *barWait );
237        if ( ticket == -1 ) {
238                insert( *barWait, -1 );
239                return;
240        }
241
242        // last one out
243        if ( size == 1 || ticket == size - 2 ) {
244                for ( j; size )
245                        insert( *entryWait, j );
246        }
247}
248barrier b;
249
250bool done = false;
251// thread main
252void main(Task & this) {
253        for ( ;; ) {
254                if ( done ) break;
255                wait( b );
256        }
257}
258
259int main() {
260        {
261                Task t[Tasks];
262
263                sleep(10`s);
264                done = true;
265
266                flush( b );
267        } // wait for tasks to terminate
268        return 0;
269}
270\end{cfa}
271
272In Listing~\ref{l:cfa_resume} an example of channel closing with resumption is used.
273This program uses resumption in the @Consumer@ thread main to ensure that all elements in the channel are removed before the consumer thread terminates.
274The producer only has a @catch@ so the moment it receives an exception it terminates, whereas the consumer will continue to remove from the closed channel via handling resumptions until the buffer is empty, which then throws a termination exception.
275If the same program was implemented in Go it would require explicit synchronization with both producers and consumers by some mechanism outside the channel to ensure that all elements were removed before task termination.
276
277\begin{cfa}[caption={\CFA channel resumption usage},label={l:cfa_resume}]
278channel( int ) chan{ 128 };
279
280// Consumer thread main
281void main(Consumer & this) {
282        size_t runs = 0;
283        try {
284                for ( ;; ) {
285                        remove( chan );
286                }
287        } catchResume ( channel_closed * e ) {}
288        catch ( channel_closed * e ) {}
289}
290
291// Producer thread main
292void main(Producer & this) {
293        int j = 0;
294        try {
295                for ( ;;j++ ) {
296                        insert( chan, j );
297                }
298        } catch ( channel_closed * e ) {}
299}
300
301int main( int argc, char * argv[] ) {
302        {
303                Consumers c[4];
304                Producer p[4];
305
306                sleep(10`s);
307
308                for ( i; Channels )
309                        close( channels[i] );
310        }
311        return 0;
312}
313\end{cfa}
314
315\section{Performance}
316
317Given that the base implementation of the \CFA channels is very similar to the Go implementation, this section aims to show that the performance of the two implementations are comparable.
318One microbenchmark is conducted to compare Go and \CFA.
319The benchmark is a ten second experiment where producers and consumers operate on a channel in parallel and throughput is measured.
320The number of cores is varied to measure how throughput scales.
321The cores are divided equally between producers and consumers, with one producer or consumer owning each core.
322The results of the benchmark are shown in Figure~\ref{f:chanPerf}.
323The performance of Go and \CFA channels on this microbenchmark is comparable.
324Note, it is expected for the performance to decline as the number of cores increases as the channel operations all occur in a critical section so an increase in cores results in higher contention with no increase in parallelism.
325
326
327\begin{figure}
328        \centering
329        \subfloat[AMD \CFA Channel Benchmark]{
330                \resizebox{0.5\textwidth}{!}{\input{figures/nasus_Channel_Contention.pgf}}
331                \label{f:chanAMD}
332        }
333        \subfloat[Intel \CFA Channel Benchmark]{
334                \resizebox{0.5\textwidth}{!}{\input{figures/pyke_Channel_Contention.pgf}}
335                \label{f:chanIntel}
336        }
337        \caption{The channel contention benchmark comparing \CFA and Go channel throughput (higher is better).}
338        \label{f:chanPerf}
339\end{figure}
340
341% Local Variables: %
342% tab-width: 4 %
343% End: %
Note: See TracBrowser for help on using the repository browser.