-1

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?

ceving
  • 21,900
  • 13
  • 104
  • 178
  • 4
    Start a goroutine to read from each connection. – Charlie Tumahai Mar 26 '19 at 16:44
  • @CeriseLimón I need the input from the two connections in one function. Like an adder: read `a` from connection 1, `b` from connection 2 and return `a+b`. The function should not care, which value arrives first, but should wait until both values have been read. – ceving Mar 26 '19 at 16:52
  • 2
    Then you not even need a select, just read from both, e.g. from two goroutines and combine via one channel and to receives. – Volker Mar 26 '19 at 20:34

1 Answers1

1
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
        }
    }
}
Andonaeus
  • 872
  • 1
  • 5
  • 21