官术网_书友最值得收藏!

Channel

Channels are used to communicate between threads. Channels are first-in, first-out (FIFO) queues. You can push objects on to the queue and pull from the front asynchronously. Each channel can only support one data type. Channels are blocking by default, but can be made nonblocking with a select statement. Like slices and maps, channels must be initialized before use with the make() function.

The saying in Go is Do not communicate by sharing memory; instead, share memory by communicating. Read more about this philosophy at https://blog.golang.org/share-memory-by-communicating.

Here is an example program that demonstrates basic channel usage:

package main

import (
"log"
"time"
)

// Do some processing that takes a long time
// in a separate thread and signal when done
func process(doneChannel chan bool) {
time.Sleep(time.Second * 3)
doneChannel <- true
}

func main() {
// Each channel can support one data type.
// Can also use custom types
var doneChannel chan bool

// Channels are nil until initialized with make
doneChannel = make(chan bool)

// Kick off a lengthy process that will
// signal when complete
go process(doneChannel)

// Get the first bool available in the channel
// This is a blocking operation so execution
// will not progress until value is received
tempBool := <-doneChannel
log.Println(tempBool)
// or to simply ignore the value but still wait
// <-doneChannel

// Start another process thread to run in background
// and signal when done
go process(doneChannel)

// Make channel non-blocking with select statement
// This gives you the ability to continue executing
// even if no message is waiting in the channel
var readyToExit = false
for !readyToExit {
select {
case done := <-doneChannel:
log.Println("Done message received.", done)
readyToExit = true
default:
log.Println("No done signal yet. Waiting.")
time.Sleep(time.Millisecond * 500)
}
}
}
主站蜘蛛池模板: 花莲县| 武功县| 崇明县| 襄樊市| 六盘水市| 乾安县| 滦南县| 黔东| 绥江县| 湖北省| 平度市| 彭阳县| 闽清县| 乌兰浩特市| 正定县| 临桂县| 台湾省| 南阳市| 酒泉市| 政和县| 民县| 库车县| 万荣县| 馆陶县| 塘沽区| 崇礼县| 海兴县| 互助| 吉木萨尔县| 霍林郭勒市| 嘉鱼县| 山丹县| 文昌市| 东光县| 新密市| 吐鲁番市| 贞丰县| 叙永县| 山丹县| 鹤岗市| 永川市|