Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Last active May 5, 2020 16:53
Show Gist options
  • Save olehcambel/6f22db8f2d7bd4102ec466786cc30d0a to your computer and use it in GitHub Desktop.
Save olehcambel/6f22db8f2d7bd4102ec466786cc30d0a to your computer and use it in GitHub Desktop.
buffered/unbuffered channel impl.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int) // Allocate a channel.
// uncomment this line
// c := make(chan int, 1) // Allocate a channel.
// Start the sort in a goroutine; when it completes, signal on the channel.
go func() {
time.Sleep(time.Second * 1)
// sort.Sort()
c <- 1 // Send a signal; value does not matter.
fmt.Println("c <- 1")
time.Sleep(time.Second * 2)
}()
time.Sleep(time.Second * 10)
// doSomethingForAWhile()
<-c // Wait for sort to finish; discard sent value.
fmt.Println("<-c")
time.Sleep(time.Second * 2)
}
@olehcambel
Copy link
Author

Receivers always block until there is data to receive. If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment