-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconcurrency.tex
90 lines (78 loc) · 3.4 KB
/
concurrency.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Go Concurrency Patterns}
\chapter*{Go Concurrency Patterns}
\section*{Timing out, moving on}
Concurrent programming has its own idioms. A good example is timeouts.
Although Go's channels do not support them directly, they are easy to
implement. Say we want to receive from the channel \texttt{ch}, but want
to wait at most one second for the value to arrive. We would start by
creating a signalling channel and launching a goroutine that sleeps
before sending on the channel:
\begin{Verbatim}[frame=single]
timeout := make(chan bool, 1)
go func() {
time.Sleep(1 * time.Second)
timeout <- true
}()
\end{Verbatim}
We can then use a \texttt{select} statement to receive from either
\texttt{ch} or \texttt{timeout}. If nothing arrives on \texttt{ch} after
one second, the timeout case is selected and the attempt to read from
\texttt{ch} is abandoned.
\begin{Verbatim}[frame=single]
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}
\end{Verbatim}
The \texttt{timeout} channel is buffered with space for 1 value,
allowing the timeout goroutine to send to the channel and then exit. The
goroutine doesn't know (or care) whether the value is received. This
means the goroutine won't hang around forever if the \texttt{ch} receive
happens before the timeout is reached. The \texttt{timeout} channel will
eventually be deallocated by the garbage collector.
(In this example we used \texttt{time.Sleep} to demonstrate the
mechanics of goroutines and channels. In real programs you should use
\texttt{ time.After}, a function that returns a channel and sends on
that channel after the specified duration.)
Let's look at another variation of this pattern. In this example we have
a program that reads from multiple replicated databases simultaneously.
The program needs only one of the answers, and it should accept the
answer that arrives first.
The function \texttt{Query} takes a slice of database connections and a
\texttt{query} string. It queries each of the databases in parallel and
returns the first response it receives:
\begin{Verbatim}[frame=single]
func Query(conns []Conn, query string) Result {
ch := make(chan Result, 1)
for _, conn := range conns {
go func(c Conn) {
select {
case ch <- c.DoQuery(query):
default:
}
}(conn)
}
return <-ch
}
\end{Verbatim}
In this example, the closure does a non-blocking send, which it achieves
by using the send operation in \texttt{select} statement with a
\texttt{default} case. If the send cannot go through immediately the
default case will be selected. Making the send non-blocking guarantees
that none of the goroutines launched in the loop will hang around.
However, if the result arrives before the main function has made it to
the receive, the send could fail since no one is ready.
This problem is a textbook example of what is known as a
\href{https://en.wikipedia.org/wiki/Race\_condition}{race condition},
but the fix is trivial. We just make sure to buffer the channel
\texttt{ch} (by adding the buffer length as the second argument to
\href{/pkg/builtin/\#make}{make}), guaranteeing that the first send has
a place to put the value. This ensures the send will always succeed, and
the first value to arrive will be retrieved regardless of the order of
execution.
These two examples demonstrate the simplicity with which Go can express
complex interactions between goroutines.