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

  • Security with Go
  • John Daniel Leon
  • 297字
  • 2021-06-30 19:06:48

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)
}
}
}
主站蜘蛛池模板: 洪泽县| 黄大仙区| 莒南县| 新蔡县| 伊吾县| 盘山县| 西平县| 永胜县| 萝北县| 阳山县| 大姚县| 金阳县| 金堂县| 溆浦县| 上犹县| 土默特右旗| 乐安县| 望江县| 南溪县| 婺源县| 临高县| 舒城县| 雷山县| 商水县| 凌源市| 峡江县| 清水河县| 玉林市| 石林| 江川县| 略阳县| 龙泉市| 新安县| 修水县| 英德市| 辛集市| 商城县| 铜鼓县| 纳雍县| 仁寿县| 东平县|