Ask Your Question
3

How can several goroutines access a shared channel for reading data?

asked 2021-12-08 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-01-27 01:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-08 11:00:00 +0000

Seen: 9 times

Last updated: Jan 27 '22