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