Saluran Golang
// When we send data into the channel using a GoRoutine,
// it will be blocked until the data is consumed by another GoRoutine.
// When we receive data from channel using a GoRoutine,
// it will be blocked until the data is available in the channel.
func main() {
runIncrement()
}
func runIncrement() {
channel := make(chan string)
go increment(channel)
time.Sleep(1 * time.Second)
for msg := range channel {
fmt.Println(msg)
}
}
func increment(channel chan string) {
for i := 0; i < 3; i++ {
channel <- "Hello Wordl"
}
time.Sleep(1 * time.Second)
close(channel)
}
func runCounter() {
channel := make(chan string)
wg := sync.WaitGroup{}
wg.Add(1)
go counter(channel, &wg)
for msg := range channel {
fmt.Println(msg)
}
wg.Wait()
}
func counter(channel chan string, wg *sync.WaitGroup) {
for i := 0; i < 3; i++ {
channel <- "Hello world"
}
wg.Done()
close(channel)
}
Restu Wahyu Saputra