Golang Learning excerpt Seven: concurrency

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

Go uses channel and goroutine to develop parallel programs. Goroutine is the core element of go concurrency capability.
Goroutine is a normal function, just need to use the keyword go as the beginning.

ready("Tea", 2) // 普通函数调用go ready("Tea", 2) // ready() 作为 goroutine 运行

Go Routine Practice

func ready(w string, sec int) {  time.Sleep(time.Duration(sec) * time.Second)  fmt.Println(w,"is ready!")}func main() {  go ready("Tea", 2)  go ready("Coffee", 1)   fmt.Println("I'm waiting")   time.Sleep(5 * time.Second)}// 输出  I'm waiting //立刻Coffee is ready! //1秒后Tea is ready! //2秒回

If you do not wait for Goroutine to execute (such as removing line 17th), the program terminates immediately and any goroutine that are executing will stop. In order to repair the use of channels mechanism to communicate with Goroutine. Values can be sent or accepted through the channel. These values can only be of a specific type: Channel type.
Note that you must use make to create the channel:

ci := make(chan int) //创建 channel ci 用于发送和接收整数cs := make(chan string) //创建 channel cs 用于字符串cf:=make(chan interface{})//channel cf 使用了空接口来满足各种类型

Sending or receiving data to the channel is done by a similar operator: <−. The specific action depends on the position of the operator:

ci <− 1 // 发送整数 1 到 channelci<−ci // 从 channel ci 接收整数i := <−ci // 从 channel ci 接收整数,并保存到 i 中

The above example uses the channel to become:

  var c chan Int//defines c as the channel of the int type. That means: This channel transmits integers. Note that this variable is global so that goroutine can access it; Func Ready (W string, sec int) {time. Sleep (time. Duration (SEC) * time. Second) fmt.    Println (W, "is ready!") C <-1//Send integer 1 to channel C;}  Func Main () {c=make (chan int)//initialize C;  Go Ready ("Tea", 2)//Use the keyword go to start a goroutine; Go Ready ("Coffee", 1) fmt. Println ("I ' m waiting, but not too long") <−c//waits until a value is received from the channel.  Note that the received value is discarded; <−c//two goroutines, receives two values. }//If you do not know how many goroutine are started, you can use Select to listen for data entered on the channel l:for {select {case <−c:i++ if i>1{break L}}}//will be waiting for you now. The Loop L is exited only if multiple responses are received from channel C. 

Although Goroutine are executed concurrently, they are not run in parallel. If you don't tell Go extras, only one goroutine will be executed at the same time. Use runtime. Gomaxprocs (n) can set the number of Goroutine parallel executions. If you do not want to modify any source code, you can also set the environment variable Gomaxprocs as the target value.
When you create a chennel with ch: = Make (chan bool) in Go, the bool-type unbuffered channel is created. The channel can also specify a buffer size, ch: = Make (chan bool, 4), creating a bool channel that can store 4 elements. In this channel, the first 4 elements can be written without blocking. When the 5th element is written, the code blocks until the other goroutine reads some elements from the channel, freeing up space.

When the channel is closed, the reader needs to know about it.

x, ok = <−ch

When OK is assigned true means that the channel has not been closed and the data can be read. Otherwise OK is assigned to false. In this case, the channel is closed.

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.