…a means of communication
Björn Andersson
stopChan := make(chan bool)
, create a channel<-c
: read from a channelc <-
: write to a channelname <-chan string
: read-onlyname chan<- string
: write-only
greetingChan := make(chan string)
go func (c <-chan string) {
fmt.Printf("Hello, %s", <-c)
}(greetingChan)
greetingChan <- "World"
With channels you can share a limited resource across unlimited concurrency
var dbConns []*DB.Conn // assume it contains 5 connections
dbPool := make(chan *DB.Conn, 5)
for i := 0; i < 5; i++ {
dbPool <-dbConns[i]
}
t.Run("parallel test run 1", func (t *testing.T) {
t.Parallel()
db := <- dbPool
defer func () { dbPool <- db }() // returns to pool
// run lots of tests
})
stopChan := make(chan struct{})
close(stopChan) // No value written to the channel
v, ok := <- stopChan
fmt.Printf("v=%v, open=%v\n", v, ok) // v=false, open=false
v, ok = <- stopChan
fmt.Printf("v=%v, open=%v\n", v, ok) // v=false, open=false
func getMessages(
ctx context.Context,
query Query,
errChan chan<- error,
stopChan <-chan struct{},
) {}
context.Context
means external shutdownerrChan
sounds like there can be errors that forces the function to stop
work on its own
stopChan
tells me that there are other reasons than context to stop
working
select
statementswitch
statement, but for channelsdefault
evaluates immediately if no channel is readable
default