Go通道範例


通道是連線並行goroutine的管道。可以從一個goroutine向通道傳送值,並在另一個goroutine中接收到這些值。

使用make(chan val-type)建立一個新通道,通道由輸入的值傳入。使用通道 <- 語法將值傳送到通道。 這裡從一個新的goroutine傳送「ping」到在上面的訊息通道。

<-channel語法從通道接收值。在這裡,將收到上面傳送的「ping」訊息並列印出來。當執行程式時,「ping」訊息通過通道成功地從一個goroutine傳遞到另一個goroutine。預設情況下傳送和接收塊,直到傳送方和接收方都準備好。此屬性允許在程式結束時等待「ping」訊息,而不必使用任何其他同步。

所有的範例程式碼,都放在 F:\worksp\golang 目錄下。安裝Go程式設計環境請參考:/2/23/798.html

channels.go的完整程式碼如下所示 -

package main

import "fmt"

func main() {

    // Create a new channel with `make(chan val-type)`.
    // Channels are typed by the values they convey.
    messages := make(chan string)

    // _Send_ a value into a channel using the `channel <-`
    // syntax. Here we send `"ping"`  to the `messages`
    // channel we made above, from a new goroutine.
    go func() { messages <- "ping" }()

    // The `<-channel` syntax _receives_ a value from the
    // channel. Here we'll receive the `"ping"` message
    // we sent above and print it out.
    msg := <-messages
    fmt.Println(msg)
}

執行上面程式碼,將得到以下輸出結果 -

F:\worksp\golang>go run channels.go
ping