示例代碼
package main
import (
"fmt"
"sync"
)
func sendMsg(msg_ch chan string, wg *sync.WaitGroup) {
fmt.Println("sendMsg start")
msg_ch <- "hello 1" //向通道中寫資料
fmt.Println("sendMsg end")
wg.Done()
}
func recvMsg(msg_ch chan string, wg *sync.WaitGroup) {
fmt.Println("recvMsg start")
msg := <- msg_ch //阻塞等待通道資料可讀
fmt.Println("msg:", msg)
fmt.Println("recvMsg end")
wg.Done()
}
func main() {
fmt.Println("00")
wg := sync.WaitGroup{}
wg.Add(2)
msg_ch := make(chan string) //通過channel來通信
go sendMsg(msg_ch, &wg) //啟動roroutine并發執行
go recvMsg(msg_ch, &wg) //啟動roroutine并發執行
fmt.Println("11")
wg.Wait() //等待全部goroutine結束
fmt.Println("22")
}
運作結果
00
11
recvMsg start
sendMsg start
sendMsg end
msg: hello 1
recvMsg end
22