Use and summary of the channel of Go

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

The channel is used for communication between the master process and the association.

1. Sync mode
The channel defaults to synchronous mode, that is, no buffer is created, one by one pairing is required for sending and receiving, otherwise the sender is blocked until the data is received. It is important to note that the synchronized channel cannot be sent & received in one process because it will be blocked and never run to the received statement. One of the simplest examples:

package mainimport "fmt"func main() {    data := make(chan int)    go func() {        for d := range data {//通过range不断地处理data            fmt.Println(d)        }    }()        data <- 1//发送要放在接收协程跑起来后面,因为发送后会阻塞等待接收    data <- 2    data <- 3    close(data)}

or receive the channel in this way, if!ok indicates that data is close:

go func() {        for {            if d, ok := <-data; ok {                fmt.Println(d)            }        }    }()

2. Asynchronous mode
The asynchronous mode channel has a buffer, if the buffer is full, the sending of the main process or the association will be blocked, if not full will not be blocked, if empty, the received coprocessor will be blocked. Based on this nature, it is often necessary to have a synchronous channel to control whether the main process exits, otherwise it is possible that the process has not finished processing all the information, the main processes have exited. It is also important to note that the asynchronous channel runs out to close, otherwise the channel that handles this will be blocked, forming a deadlock.

package mainimport "fmt"func main() {    data := make(chan int, 3)    canQuit := make(chan bool) //阻塞主进程,防止未处理完就退出    go func() {        for d := range data {//如果data的缓冲区为空,这个协程会一直阻塞            fmt.Println(d)        }        canQuit <- true    }()    data <- 1    data <- 2    data <- 3    data <- 4    data <- 5    close(data) //用完需要关闭,否则goroutine会被死锁    <-canQuit //解除阻塞}

Use of 3.select
Actually, the channel is usually used in the actual project.

Package Mainimport "FMT" Import "Time" import "OS" const (max_request_num = Cmd_user_pos = 1) var (save Chan  BOOL Quit Chan bool req chan *request) type Request struct {CmdID int16 Data interface{}}type userpos struct            {X int16 Y int16}func Main () {newreq: = request{Cmdid:cmd_user_pos, data:userpos{ X:10, Y:20,},} go Handler () Req <-&newreq time. Sleep (*. Millisecond) Save <-True Close (req) <-quit}func handler () {for {select {case <-save                : Savegame () case R, OK: = <-req:if OK {onreq (r)} else { Fmt.                Println ("req Chan closed.") Os.    Exit (0)}}}}func init () {req = make (chan *request, max_request_num) Save = make (chan bool) Quit = Make (chan bool)}func savegame () {fmt. Printf ("Do Something with Save game.\n") Quit <-True}func Onreq (R *request) {pos: = R.data. ( Userpos) fmt. Println (R.cmdid, POS)}

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.