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

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)
}
}
}
主站蜘蛛池模板: 大荔县| 垣曲县| 太仆寺旗| 大新县| 鹤山市| 收藏| 通河县| 金秀| 库伦旗| 江都市| 阳春市| 平远县| 平武县| 化州市| 招远市| 江口县| 荥经县| 廊坊市| 河津市| 阜宁县| 隆子县| 鱼台县| 丹江口市| 方山县| 和平区| 马鞍山市| 镇沅| 临邑县| 大理市| 连山| 集贤县| 静安区| 桦甸市| 许昌市| 监利县| 沅江市| 务川| 曲水县| 五华县| 黄冈市| 湖州市|