Sync and channel synchronization mechanism in Golang

Source: Internet
Author: User

Sync instance:

Package Main

Import (
"FMT"
"Sync"
)

var waitgroup sync. Waitgroup

Func afunction (shownum int) {
Fmt. Println (Shownum)
Waitgroup. Done ()//task completed, number of tasks in the task queue-1, in fact. Done is. ADD (-1)
}

Func Main () {
For I: = 0; I < 10; i++ {
Waitgroup. ADD (1)//Each creation of a goroutine, the number of tasks in the task queue +1
Go afunction (i)
}
Waitgroup. Wait ()//. Wait () This will block until all the tasks in the queue are terminated.
}

Non-cached channel instances:

Package Main

Import "FMT"

Func afuntion (ch Chan int) {
Fmt. Println ("Finish")
<-ch
}

Func Main () {
CH: = make (chan int)//unbuffered Channel
Go afuntion (CH)
CH <-1

Output Result:
Finish
}

There are cached channel instances:

Package Main

Import "FMT"

Func Main () {
var ch = make (chan int, 20)
For I: = 0; I < 10; i++ {
CH <-I
}
Close (CH)
CH <-//panic:runtime error:send on closed channel
For i: = Range ch {
Fmt. PRINTLN (i)//Output 0 1 2 3 4 5 6 7 8 9
}
}

Time-out processing channel instances:

Package Main

Import (
"FMT"
"Time"
)

Func Main () {
c: = make (chan int)
O: = Make (chan bool)
Go func () {
for {
Select {
case I: = <-c:
Fmt. Println (i)
Case <-time. After (time. Duration (3) * time. Second)://Set timeout of 3s, if the channel 3s clock is not responding, has been blocked, the report timed out, time-out processing.
Fmt. PRINTLN ("timeout")
O <-True
Break
}
}
}()
<-o
}

Sync and channel synchronization mechanism in Golang

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.