sync實例:php
package main
import (
"fmt"
"sync"
)
var waitgroup sync.WaitGroup
func Afunction(shownum int) {
fmt.Println(shownum)
waitgroup.Done() //任務完成,將任務隊列中的任務數量-1,其實.Done就是.Add(-1)
}
func main() {
for i := 0; i < 10; i++ {
waitgroup.Add(1) //每建立一個goroutine,就把任務隊列中任務的數量+1
go Afunction(i)
}
waitgroup.Wait() //.Wait()這裏會發生阻塞,直到隊列中全部的任務結束就會解除阻塞
}golang
無緩存的channel實例:緩存
package main
import "fmt"
func Afuntion(ch chan int) {
fmt.Println("finish")
<-ch
}
func main() {
ch := make(chan int) //無緩衝的channel
go Afuntion(ch)
ch <- 1
// 輸出結果:
// finish
}app
有緩存的channel實例:ui
package main
import "fmt"
func main() {
var ch = make(chan int, 20)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
//ch <- 11 //panic: runtime error: send on closed channel
for i := range ch {
fmt.Println(i) //輸出0 1 2 3 4 5 6 7 8 9
}
}
url
超時處理channel實例:spa
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): //設置超時時間爲3s,若是channel 3s鐘沒有響應,一直阻塞,則報告超時,進行超時處理.
fmt.Println("timeout")
o <- true
break
}
}
}()
<-o
}
3d