This is a creation in Article, where the information may have evolved or changed.
<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " The channel of >go language is a very important part, because the core of go-concurrency must use this .</span>
We know that concurrency is a lot of time to communicate. The concurrent communication of the Go language is the recommendation that we use the channel, which is the concurrent communication based on the message-passing model.
(1) Create channel.
The built-in type in go, we use make (custom type uses new--to return the object pointer)
CH: = make (chan int)
This creates a channel and, of course, I can declare it first, in the assignment creation.
var ch Chan int
ch = make (chan int)
(2) with cushioning
CH: = Make (chan int, 10)
The above meaning is to create a channel named CH, the type is int, the buffer value is 10.
What is buffering?
If we do not have this buffer value, we must be ready in the channel when we read the channel, otherwise it will block up. When writing, be sure to have no value inside, otherwise it will block. Hangs the program, deadlocks.
With this buffer value, if we have a <=10 value in the channel, I read it without blocking and returning immediately. In the <10 of the inside, the write is also returned in an instant. This will not suspend the program.
(3) We can also create one-way, and two-way channel. This is created from the existing channel, with only a few constraints.
(4) Reading channel
Value: = <-ch
(5) Write channel
CH <-Value
(6) Range syntax.
For one: = Range chout { //one}
The range above should be noted that if Chout does not explicitly close the channel after the producer has placed the data, the range is blocked in that thread.
Because range does not see the explicit shutdown of the channel, it does not stop.
There are two solutions:
1 explicitly shuts down after data is placed in the channel.
Close (chout)
2 judge
For one: = Range Chout {if I: = Len (chout), I <= 0 {break}}