2024-04-27 09:50:18 +00:00
|
|
|
package channels
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"unicode/utf8"
|
|
|
|
)
|
|
|
|
|
|
|
|
func header(title string) {
|
|
|
|
fmt.Println(strings.Repeat("-", utf8.RuneCountInString(title)))
|
|
|
|
fmt.Println(title)
|
|
|
|
fmt.Println(strings.Repeat("-", utf8.RuneCountInString(title)))
|
|
|
|
fmt.Println()
|
|
|
|
}
|
|
|
|
|
|
|
|
func simpleChannels() {
|
|
|
|
header("Simple channels")
|
|
|
|
|
|
|
|
message := make(chan string)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
message <- "beep bop!"
|
|
|
|
}()
|
|
|
|
|
|
|
|
msg := <-message
|
|
|
|
fmt.Println("Received secret message:", msg)
|
|
|
|
fmt.Println("Done")
|
|
|
|
}
|
|
|
|
|
|
|
|
func bufferedChannels() {
|
|
|
|
header("Buffered channels")
|
|
|
|
|
|
|
|
message := make(chan string, 2)
|
|
|
|
|
|
|
|
message <- "secret 1!"
|
|
|
|
message <- "secret 2!"
|
|
|
|
|
|
|
|
fmt.Println("First message:", <-message)
|
|
|
|
fmt.Println("Second message:", <-message)
|
|
|
|
fmt.Println("Done")
|
|
|
|
}
|
|
|
|
|
2024-04-28 09:57:07 +00:00
|
|
|
func ping(pingc chan<- string, msg string) {
|
|
|
|
pingc <- msg
|
|
|
|
}
|
|
|
|
|
|
|
|
func pong(pingc <-chan string, pongc chan<- string) {
|
|
|
|
fmt.Println("pong() received message:", <-pingc)
|
|
|
|
pongc <- "pong!"
|
|
|
|
}
|
|
|
|
|
|
|
|
func pingPong() {
|
|
|
|
header("Channel Directions")
|
|
|
|
pingc, pongc := make(chan string, 1), make(chan string, 1)
|
|
|
|
ping(pingc, "ping!")
|
|
|
|
pong(pingc, pongc)
|
|
|
|
fmt.Println("Received message in pingPong():", <-pongc)
|
|
|
|
}
|
|
|
|
|
2024-04-27 09:50:18 +00:00
|
|
|
func Channels() {
|
|
|
|
simpleChannels()
|
|
|
|
bufferedChannels()
|
2024-04-28 09:57:07 +00:00
|
|
|
pingPong()
|
2024-04-27 09:50:18 +00:00
|
|
|
}
|