Last active
May 5, 2020 16:53
-
-
Save olehcambel/6f22db8f2d7bd4102ec466786cc30d0a to your computer and use it in GitHub Desktop.
buffered/unbuffered channel impl.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.