1.返回值使用通道
func main() { // 生成隨機(jī)數(shù)作為一個(gè)服務(wù) randService := randGenerator() // 從服務(wù)中讀取隨機(jī)數(shù)并打印 fmt.Printf("%d\n",<-randService)}func randGenerator() chan int { // 創(chuàng)建通道 out := make(chan int) // 創(chuàng)建協(xié)程 go func() { for { //向通道內(nèi)寫入數(shù)據(jù),如果無人讀取會(huì)等待 out <- rand.Int() } }() return out}
2.參數(shù)使用通道
//一個(gè)查詢結(jié)構(gòu)體type query struct { //參數(shù)Channel sql chan string //結(jié)果Channel result chan string}//執(zhí)行Queryfunc execQuery(q query) { //啟動(dòng)協(xié)程 go func() { //獲取輸入 sql := <-q.sql //訪問數(shù)據(jù)庫,輸出結(jié)果通道 q.result <- "get" + sql }()}func main() { //初始化Query q := query{make(chan string, 1),make(chan string, 1)} //執(zhí)行Query,注意執(zhí)行的時(shí)候無需準(zhǔn)備參數(shù) execQuery(q) //準(zhǔn)備參數(shù) q.sql <- "select * from table" //獲取結(jié)果 fmt.Println(<-q.result)}
3.并發(fā)循環(huán)
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() { // 建立計(jì)數(shù)器,通道大小為cpu核數(shù) var NumCPU = runtime.NumCPU() fmt.Printf("NumCPU = %d\n", NumCPU) sem :=make(chan int, NumCPU); //FOR循環(huán)體 data := []int{1, 11, 21, 31, 41, 51, 61, 71, 81, 91} for _,v:= range data { //建立協(xié)程 go func (v int) { fmt.Printf("doSomething(%d)...\n", v) sum := doSomething(v); //計(jì)數(shù) sem <- sum; } (v); } // 等待循環(huán)結(jié)束 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計(jì)算素?cái)?shù)
// 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.共享變量的讀寫
//共享變量有一個(gè)讀通道和一個(gè)寫通道組成type shardedVar struct { reader chan int writer chan int}//共享變量維護(hù)協(xié)程func whachdog(v shardedVar) { go func() { //初始值 var value int = 0 for { //監(jiān)聽讀寫通道,完成服務(wù) select { case value = <-v.writer: case v.reader <-value: } } }()}func main() { //初始化,并開始維護(hù)協(xié)程 v := shardedVar{make(chan int), make(chan int)} whachdog(v) //讀取初始值 fmt.Println(<-v.reader) //寫入一個(gè)值 v.writer <- 1 //讀取新寫入的值 fmt.Println(<-v.reader)}
還可以訪問我樹莓派上搭的博客地址:
聯(lián)系客服