0

so my question is how to send message to channels that broadcast function gets only if channel is not closed and just for once.

after sending message should increase sentNumber.

I say just to remind, there is a time limit for sending message to all channels!

package main

import (
    "fmt"
    "sync"
    "time"
)

var (
    sentNumber int
)

func broadcast(waitTime time.Duration, message string, ch ...chan string) (sentNumber int) {
    start := time.Now()
    for _, channel := range ch {
        if time.Since(start) >= waitTime {
            break
        }
        go send(channel, message)
    }
    return 0
}

func send(channel chan string, message string) {
    for {
        if _,open := <-channel; open{
            break
        }
    }
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        wg.Done()
        channel <- message
    }()
    wg.Wait()
}

func main() {
    a := make(chan string, 1)
    b := make(chan string, 1)
    broadcast(5, "secret message", a, b)
    fmt.Println(<-a)
    fmt.Println(<-b)
}

1 Answers1

1
  1. time.Since(start) >= waitTime can't break the send function
  2. go send(channel, message) should not be more efficient than a single thread queue in this case
  3. broadcast has no responsibility to check if channel has been closed, channels were not created/closed by broadcast
package main

import (
    "context"
    "fmt"
    "time"
)

func broadcast(waitTime time.Duration, message string, chs ...chan string) (sentNumber int) {
    ctx, cancel := context.WithTimeout(context.Background(), waitTime)
    defer cancel()

    jobQueue := make(chan chan string, len(chs))
    for _, c := range chs {
        jobQueue <- c
    }

queue:
    for c := range jobQueue {
        select {
        case c <- message:
            // sent success
            sentNumber += 1
            if sentNumber == len(chs) {
                cancel()
            }
        case <-ctx.Done():
            // timeout, break job queue
            break queue
        default:
            // if send failed, retry later
            jobQueue <- c
        }
    }

    return
}

func main() {
    a := make(chan string)
    b := make(chan string)

    go func() {
        time.Sleep(time.Second)
        fmt.Println("a:", <-a)
    }()

    go func() {
        time.Sleep(3 * time.Second)
        fmt.Println("b:", <-b)
    }()

    c := broadcast(2*time.Second, "secret message", a, b)
    fmt.Printf("sent count:%d\n", c)

    time.Sleep(3 * time.Second)
}
emptyhua
  • 6,634
  • 10
  • 11