Go's channel explanation

Source: Internet
Author: User

The channel is not assigned to the data when it is blocked, you can use this mechanism to complete the monitoring of the event

WG: = new (sync. WAITGROUP) WG. ADD (2) Event: = Make (chan bool)//Function go func () {defer WG. Done () for I: = 0; I < 5; i++ {fmt. Println ("Before Trigger event", I)}event <-true//Trigger event} () go func () {<-eventdefer WG. Done () for I: = 0; I < 5; i++ {fmt. Println ("After triggering event", I)}} () WG. Wait ()

Output:

0 before triggering event
1 before triggering event
2 before triggering event
3 before triggering event
4 before triggering event
0 after triggering event
1 after triggering event
2 after triggering event
3 after triggering event
4 after triggering event

When using the channel, be aware that

If Chan's capacity is full, a deadlock will occur

Such as:

Data:=make (chan int, 3) Exit:=make (chan bool) data<-1data<-2data<-3data<-4//run here will be blocked because Chan capacity is full

 

Len returns the number of elements that have not been read in Chan, the cap returns the buffer size, close closes the current Chan

Judge Chan whether to close

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

  

One-way Chan: only responsible for receiving, or only responsible for sending

Equivalent to separating Chan's send and receive, turning it into two easy-to-control variables

c: = make (chan int, 3) var send chan<-int = c//send-onlyvar recv <-chan int = c//receive-onlysend <-1<-re Cv

  

Go's channel explanation

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.