1.返回值使用通道sql
func main() { // 生成隨機數做爲一個服務 randService := randGenerator() // 從服務中讀取隨機數並打印 fmt.Printf("%d\n",<-randService) } func randGenerator() chan int { // 建立通道 out := make(chan int) // 建立協程 go func() { for { //向通道內寫入數據,若是無人讀取會等待 out <- rand.Int() } }() return out }
2.參數使用通道數據庫
//一個查詢結構體 type query struct { //參數Channel sql chan string //結果Channel result chan string } //執行Query func execQuery(q query) { //啓動協程 go func() { //獲取輸入 sql := <-q.sql //訪問數據庫,輸出結果通道 q.result <- "get" + sql }() } func main() { //初始化Query q := query{make(chan string, 1),make(chan string, 1)} //執行Query,注意執行的時候無需準備參數 execQuery(q) //準備參數 q.sql <- "select * from table" //獲取結果 fmt.Println(<-q.result) }
3.併發循環併發
func doSomething(num int) (sum int) { for i := 1; i <= 10; i++ { fmt.Printf("%d + %d = %d\n", num, num + i, num + num + i) sum = sum + num + i } return sum } func testLoop() { // 創建計數器,通道大小爲cpu核數 var NumCPU = runtime.NumCPU() fmt.Printf("NumCPU = %d\n", NumCPU) sem :=make(chan int, NumCPU); //FOR循環體 data := []int{1, 11, 21, 31, 41, 51, 61, 71, 81, 91} for _,v:= range data { //創建協程 go func (v int) { fmt.Printf("doSomething(%d)...\n", v) sum := doSomething(v); //計數 sem <- sum; } (v); } // 等待循環結束 var total int = 0 for i := 0; i < len(data); i++ { temp := <- sem fmt.Printf("%d <- sem\n", temp) total = total + temp } fmt.Printf("total = %d\n", total) } func main() { testLoop() }
4.利用channel計算素數oop
// Send the sequence 2, 3, 4, ... to channel 'in'. func Generate(ch chan int) { for i := 2; ; i++ { ch<- i // Send 'i' to channel 'in'. } } // Copy the values from channel 'in' to channel 'out', // removing those divisible by 'prime'. func Filter(in chan int, out chan int, prime int) { for { i := <-in // Receive valuefrom 'in'. if i%prime != 0 { out <- i // Send'i' to 'out'. } } } func main() { in := make(chan int) go Generate(in) // Launch Generate goroutine. for i := 0; i < 100; i++ { prime := <-in print(prime, "\n") out := make(chan int) go Filter(in, out, prime) in = out } }
5.共享變量的讀寫spa
//共享變量有一個讀通道和一個寫通道組成 type shardedVar struct { reader chan int writer chan int } //共享變量維護協程 func whachdog(v shardedVar) { go func() { //初始值 var value int = 0 for { //監聽讀寫通道,完成服務 select { case value = <-v.writer: case v.reader <-value: } } }() } func main() { //初始化,並開始維護協程 v := shardedVar{make(chan int), make(chan int)} whachdog(v) //讀取初始值 fmt.Println(<-v.reader) //寫入一個值 v.writer <- 1 //讀取新寫入的值 fmt.Println(<-v.reader) }
還能夠訪問我樹莓派上搭的博客地址:code