Golang channels tutorial
原文链接:http://guzalexander.com/2013/12/06/golang-channels-tutorial.html golang channels 入门足矣 Golanghas built-in instruments for writing concurrent programs. Placing agostatement before a function call starts the execution of that function as an independent concurrent thread in the same address space as the calling code. Such thread is called Let's start with an example of a goroutine: func main() {
// Start a goroutine and execute println concurrently
go println("goroutine message")
println("main function message")
}
This program will print As you understand there must be some way to avoid such situations. And for that there arechannelsin Golang. Channels basicsChannels serve to synchronize execution of concurrently running functions and to provide a mechanism for their communication by passing a value of a specified type. Channels have several characteristics: the type of element you can send through a channel,capacity (or buffer size) and direction of communication specified by a i := make(chan int) // by default the capacity is 0
s string, 3) // non-zero capacity
r make(<-bool) // can only read from
w chan<- []os.FileInfo) // can only write to
Channels are first-class values and can be used anywhere like other values: as struct elements,function arguments,function returning values and even like a type for another channel: // a channel which:
// - you can only write to
// - holds another channel as its value
c <- bool)
// function accepts a channel as a parameter
func readFromChannel(input string) {}
// function returns a channel
func getChannel() bool {
b bool)
return b
}
For writing and reading operations on channel there is a<-operator. Its position relatively to the channel variable determines whether it will be a read or a write operation. The following example demonstrates its usage,but I have to warn you that this codedoes not workfor some reasons described later: func main() {
c int)
c <- 42 // write to a channel
val := <-c // read from a channel
println(val)
}
Now,as we know what channels are,how to create them and perform basic operations on them,let's return to our very first example and see how channels can help us. // Create a channel to synchronize goroutines
done bool)
// Execute println in goroutine
go func() {
println("goroutine message")
// Tell the main function everything is done.
// This channel is visible inside this goroutine because
// it is executed in the same address space.
done <- true
}()
println("main function message")
<-done // Wait for the goroutine to finish
}
This program will print both messages without any possibilities. Why? In case a channel has a buffer all read operations succeed without blocking if the buffer is not empty,and write operations - if the buffer is not full. These channels are called asynchronous. Here is an example to demonstrate the difference between them: func main() {
message string) // no buffer
count := 3
func() {
for i 1; i <= count; i++ {
fmt.Println("send message")
message <- fmt.Sprintf("message %d", i)
}
}()
time.Sleep(time.Second * 3)
++ {
fmt.Println(<-message)
}
}
In this example send message
// wait for 3 seconds
message 1
send message
send message
message 2
message 3
As you see after the first write to the channel in the goroutine all other writing operations on that channel are blocked until the first read operation is performed (about 3 seconds later). Now let's provide a buffer to out send message
send message
send message
// wait for 3 seconds
message 1
message 2
message 3
Here we see that all writing operations are performed without waiting for the first read for the buffer of the channel allows to store all three messages. By changing channels capacity we can control the amount of information being processed thus limiting throughput of a system. DeadlockNow let's get back to our not working example with read/write operations. On running you'll get this error (details will differ):
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/fullpathtofile/channelsio.go:5 +0x54
exit status 2
The error you got is called adeadlock. This is a situation when two goroutines wait for each other and non of them can proceed its execution. Golang can detect deadlocks in runtime that's why we can see this error. This error occurs because of the blocking nature of communication operations. The code here runs within a single thread,line by line,successively. The operation of writing to the channel ( To make this code work we should had written something like: int)
// Make the writing operation be performed in
// another goroutine.
func() {
c 42
}()
val <-c
println(val)
}
Range channels and closingIn one of the previous examples we sent several messages to a channel and then read them. The receiving part of code was: ++ {
fmt.Println(<-message)
}
In order to perform reading operations without getting a deadlock we have to know the exact number of sent messages ( In Golang there is a so calledrange expressionwhich allows to iterate through arrays,strings,slices,maps and channels. For channels,the iteration proceeds until the channel is closed. Consider the following example (does not work for now): string)
count ++ {
message i)
}
}()
for msg := range message {
fmt.Println(msg)
}
}
Unfortunately this code does not work now. As was mentioned above the func() {
++ {
message i)
}
close(message)
}()
Closing a channel has one more useful feature - reading operations on closed channels do not block and always return default value for a channel type: done bool)
close(done)
// Will not block and will print false twice
// because it’s the default value for bool type
println(<-done)
<-done)
This feature may be used for goroutines synchronization. Let's recall one of our examples with synchronization (the one with func main() {
done bool)
// We are only interested in the fact of sending itself,
// but not in data being sent.
done <-done
}
Here the // Data is irrelevant
done chan struct{})
// Just send a signal "I'm done"
close(done)
}()
<-done
}
As we close the channel in the goroutine the reading operation does not block and the main function continues to run. Multiple channels and selectIn real programs you'll probably need more than one goroutine and one channel. The more independent parts are - the more need for effective synchronization. Let's look at more complex example: func getMessagesChannel(msg delay time.Duration) string {
c string)
<= 3; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
// Wait before sending next message
time.Sleep(time.Millisecond * delay)
}
}()
return c
}
func main() {
c1 := getMessagesChannel("first",52)">300)
c2 := getMessagesChannel("second",52)">150)
c3 := getMessagesChannel("third",52)">10)
++ {
<-c1)
<-c2)
<-c3)
}
}
Here we have a function that creates a channel and spawns a goroutine which will populate the channel with three messages in a specified interval. As we see the third channel first 1
second 1
third 1
first 2
second 2
third 2
first 3
second 3
third 3
Obviously we got a successive output. That is because the reading operation on the first channel blocks for For communication operations on multiple channels there is aselectstatement in Golang. It's much like the usual 9; i++ {
select {
case msg <-c1:
println(msg)
<-c2:
<-c3:
println(msg)
}
}
Pay attention to the number Now we get the expected output,and non of reading operations block others. The output is: first 1
second 1
third 1 // this channel does not wait for others
third 2
third 3
second 2
first 2
second 3
first 3
ConclusionChannels is a very powerful and interesting mechanism in Golang. But in order to use them effectively you have to understand how they work. In this article I tried to explain the very necessary basics. For further learning I recommend you look at the following:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |