Skip to content

Instantly share code, notes, and snippets.

@yurenchen000
Last active September 3, 2022 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurenchen000/34523dbe00d8a2a7fdbb6c8959748e30 to your computer and use it in GitHub Desktop.
Save yurenchen000/34523dbe00d8a2a7fdbb6c8959748e30 to your computer and use it in GitHub Desktop.
golang_close_chan_emulate_broadcast

go chan broadcast

chan close to emulate broadcast

if only want signal (without pass value), wait channel close can do the trick:

test code:

package main

import (
    "fmt"
    "time"
)

func wait_chan(ch <-chan int) {
    select {
    case val, ok := <-ch: //read OR closed
        fmt.Println("- got:", val, ok)
    case <-time.After(3 * time.Second):
        fmt.Println("- timeout 2")
        // default:
        // fmt.Println("immediately giveup!")
    }
}

func main() {
    fmt.Println("Broadcast emulate:")

    c2 := make(chan int, 1)
    go wait_chan(c2)
    go wait_chan(c2)
    go wait_chan(c2)

    // c2 <- 22  // ok: true , one recv
    // close(c2) // ok: false, all recv

    time.Sleep(1 * time.Second)
    close(c2)

    time.Sleep(1 * time.Second)
    fmt.Println("Finish.")
}

output:

Broadcast emulate:
- got: 0 false
- got: 0 false
- got: 0 false
Finish.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment