您好,登錄后才能下訂單哦!
1、未使用go channel
package?main import?( ????"fmt" ????"time" ) func?printer(s?string)?{ ????for?_,?v?:=?range?s?{ ????????fmt.Println(string(v)) ????????time.Sleep(time.Millisecond?*?3000) ????} } func?person()?{ ????printer("hello") } func?person2()?{ ????printer("world") } func?main()?{ ????go?person() ????go?person2() ????for?{ ????} }
d:\goprojects\src\day1\練習>go?run?main.go h w e o l r l l o d exit?status?2
2、使用channel
package?main import?( ????"fmt" ????"time" ) var?ch?=?make(chan?int,?1) func?printer(s?string)?{ ????for?_,?v?:=?range?s?{ ????????fmt.Println(string(v)) ????????time.Sleep(time.Millisecond?*?3000) ????} } func?person()?{ ????printer("hello") ????ch?<-?1 } func?person2()?{ ????<-ch ????printer("world") } func?main()?{ ????go?person() ????go?person2() ????for?{ ????} }
d:\goprojects\src\day1\練習>go?run?main.go h e l l o w o r l d
3、小結
channel?有兩端,一端寫入(數據傳入)ch<-?;一端讀出(傳出數據);要求讀寫兩端必須同時滿足條件,才能在channel上完成數據流動,否則阻塞。
4、 關閉channel
package?main import?"fmt" func?main()?{ ????ch?:=?make(chan?int) ????go?func()?{ ????????for?i?:=?0;?i?<?8;?i++?{ ????????????ch?<-?i ????????} ????????close(ch) ????}() ????for?{ ????????if?num,?ok?:=?<-ch;?ok?{ ????????????fmt.Println(num) ????????}?else?{ ????????????fmt.Println("channel?close") ????????????break ????????} ????} }
d:\goprojects\src\day1\并發\exp1>go?run?main.go 0 1 2 3 4 5 6 7 channel?close d:\goprojects\src\day1\并發\exp1>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。