First knowledge Go (8)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Concurrent

Goroutine
Goroutine is the core of Go parallel design. Goroutine is actually a thread, but he is smaller than the thread, ten
Several goroutine may be reflected in the bottom is five or six threads, the Go language inside to help you achieve these Goroutine
Memory sharing between the. Execution goroutine requires very little stack memory (presumably 4~5kb), depending on the corresponding number of
According to the scale. Because of this, thousands of concurrent tasks can be run concurrently. Goroutine is easier to use and higher than thread
Efficient and lightweight. Goroutine is a thread manager managed through the runtime of Go

Package Main
Import (
"FMT"
"Runtime"
)
Func say (s string) {
For I: = 0; I < 5; i++ {
Runtime. Gosched ()
Fmt. PRINTLN (s)
}
}
Func Main () {
Go Say ("world")//Open a new goroutines execution
Say ("Hello")//Current Goroutines execution
}
Hello World Hello World ^^ ^^ ^^ ^
It's easy to implement concurrency

Channel
The goroutine runs in the same address space, so access to shared memory must be well synchronized. So goroutine between
Where the data is communicated, Go provides a good communication mechanism for the channel. Channel can be used with Unix shell
The two-way pipeline in the analogy: you can send or receive values through it. These values can only be of a specific type: Channel class
Type. When defining a channel, you also need to define the type of value sent to the channel. Note that you must use make
Create Channel:
CI: = make (chan int)
CS: = Make (Chan string)
CF: = Make (chan interface{})

Channel via operator <-to receive and send data
CH <-v//Send V to channel Ch.
V: = <-ch//receives data from CH and assigns value to V
Write a small example:
Func sum (a []int, C Chan int) {
Sum: = 0
For _, V: = Range a {
sum + = V
}
C <-sum//send sum to C
}
Func Main () {
A: = []int{7, 2, 8,-9, 4, 0}
c: = make (chan int)
Go sum (A[:len (a)/2], C)
Go sum (A[len (a)/2:], C)
X, Y: = <-c, <-c//Receive from C
Fmt. Println (x, y, x + y)
}

Buffered Channels
We have described the default non-cached channel, but Go also allows you to specify the buffer size of the channel,
It is simple, that is, how many elements the channel can store. ch:= make (chan bool, 4), created to store 4
The bool-type channel of the element. In this channel, the first 4 elements can be written without blocking. When writing to a 5th
element, the code blocks until the other goroutine reads some elements from the channel and makes room.
CH: = Make (chan type, value)
Value = = 0! No buffering (blocking)
Value > 0! Buffering (non-blocking until value elements)

c: = make (chan int, 2)//modify 2 to 1 for error, modify 2 to 3 to run normally
C <-1
C <-2
Fmt. Println (<-C)
Fmt. Println (<-C)

Range and Close
Func Fibonacci (n int, c Chan int) {
X, Y: = 1, 1
For I: = 0; I < n; i++ {
C <-X
X, y = y, x + y
}
Close (c)//closes Chan and cannot send data after
}
Func Main () {
c: = make (chan int, 10)
Go Fibonacci (Cap (c), c)//cap,chan buffer size
For I: = range C {//can continuously read data from Chan, know Chan off
Fmt. Println (i)
}
}
Remember that the channel should be closed at the producer's place, not where it is consumed, so it can easily cause panic
Another thing to remember is that the channel is not like a file, and you don't have to close it often, only if you do not have any
Or you want to explicitly end the range loop.

Selsect
All we have described above is the case of only one channel, so if there are multiple channel, we
What to do, Go provides a keyword Select to listen to the data on the channel via select
Flow.
Select is blocked by default and will only run when there is a send or receive in the channel being monitored, when multiple
When a channel is ready, select is randomly selected for execution. We can also use Select to set timeouts,
Because the program stops there once it's blocked, we need to set the blocking timeout.
Func Main () {
c: = make (chan int)
O: = Make (chan bool)
Go func () {
for {
Select {
Case V: = <-C:
println (v)
Case <-time. After (5 * time. Second):
println ("timeout")
O <-True
Break
}
}
}()
<-o
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.