Goで拡張性のあるSelectチャンネルを作成して、Go並列プログラミングの課題を解決する
select文を使用することによって、Go言語で拡張可能な同時並行プログラミングソリューションを実現できます。select文により、複数のチャンネル操作を同時に待機できます。
まず、データと1つのチャンネルを紐づける汎用的な構造体を定義する必要があります。
type Message struct {
data interface{}
response chan interface{}
}
selectChannels 関数は任意のチャネルを受け取って非ブロッキング読み取りを実行し、チャネルのいずれかにデータが入力されるとそのデータが返される。
func selectChannels(channels ...chan interface{}) interface{} {
for {
for _, ch := range channels {
select {
case data := <-ch:
return data
default:
continue
}
}
}
}
続いて、selectChannels 関数の使用方法を示すサンプルの作成です。
func main() {
ch1 := make(chan interface{})
ch2 := make(chan interface{})
response := make(chan interface{})
go func() {
time.Sleep(time.Second)
ch1 <- "Hello"
}()
go func() {
time.Sleep(time.Second)
ch2 <- "World"
}()
go func() {
response <- selectChannels(ch1, ch2)
}()
result := <-response
fmt.Println(result)
}
上の例では、ch1とch2の2つのチャネルを作成し、selectChannels関数の結果を受け取るためのresponseチャネルを作成しました。次に、ch1とch2でそれぞれデータを送信する2つのgoroutineを作成しました。最後に、selectChannels関数を呼び出してその結果をresponseチャネルに送信するgoroutineを作成しました。最後に、responseチャネルから結果を受け取ってプリントします。
このようにすれば、拡張可能な同時並行プログラミングソリューションを簡単に構築でき、select文にて複数のchannel操作を同時に待ち受け、必要に応じてデータを処理できます。