Search code examples
goselectunix-socket

How to select in Go?


In Unix select is used to wait for more than one input source. Select waits until one input source becomes ready.

How to do this in Go?

I found a Select in Go but this seams to be a thin wrapper around the Unix function, because it works on file descriptors.

How to wait for more than one connection, in particular UnixConn connections used for Unix Domain Sockets?


Solution

  • package main
    
    import (
        "fmt"
    )
    
    type Message struct {
        Payload int
    }
    
    func main() {
        var inA *Message
        var inB *Message
    
        rxA := make(chan *Message)
        rxB := make(chan *Message)
    
        go func(txA chan *Message){
          txA <- &Message{Payload: 1} 
        }(rxA)
    
        go func(txB chan *Message){
          txB <- &Message{Payload: 2} 
        }(rxB)
    
        for {
            select {
                case inA = <- rxA:
                case inB = <- rxB:
            }
            if inA != nil && inB != nil {
                fmt.Println(inA.Payload + inB.Payload)
                break
            }
        }
    }