In Golang, several goroutines can access a shared channel for reading data by creating a single channel and passing it as an argument to all the goroutines. Each goroutine can then read from the channel independently.
For example, let's say we have two goroutines, goroutineOne
and goroutineTwo
, that need to access a shared channel for reading data. We could create the channel and pass it to the goroutines like this:
sharedChannel := make(chan int)
go goroutineOne(sharedChannel)
go goroutineTwo(sharedChannel)
Both goroutineOne
and goroutineTwo
can read from the sharedChannel
independently like this:
// goroutineOne
for data := range sharedChannel {
// do something with data
}
// goroutineTwo
for data := range sharedChannel {
// do something with data
}
Note that if one goroutine reads from the channel, the other goroutine will not receive the same data. Instead, they will each receive the next item in the channel queue. This is because a channel is designed as a first-in, first-out (FIFO) queue, so the order of data retrieval is preserved.
Asked: 2021-12-08 11:00:00 +0000
Seen: 10 times
Last updated: Jan 27 '22