xxxxxxxxxx
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
xxxxxxxxxx
package main
import (
"fmt"
"sync"
)
func main() {
greeks := []string{"plato", "socrates", "aristotle", "archimedes", "pythagoras", "democritus"}
var wg sync.WaitGroup
ch := make(chan string)
fmt.Println("Init")
for _, ph := range greeks {
wg.Add(1)
go func(str string, c chan string) {
defer wg.Done()
c <- str
}(ph, ch)
}
go func() {
wg.Wait()
defer close(ch)
}()
for c := range ch {
fmt.Println(c)
}
fmt.Println("End")
}
xxxxxxxxxx
package main
import (
"fmt"
"time"
)
func worker(id int, ch chan int) {
for {
value := <-ch
fmt.Printf("Worker %d received %d\n", id, value)
time.Sleep(time.Second) // Simulate some work
}
}
func main() {
ch := make(chan int)
// Start three worker goroutines
for i := 1; i <= 3; i++ {
go worker(i, ch)
}
// Send values to the channel
for i := 1; i <= 5; i++ {
ch <- i
}
time.Sleep(3 * time.Second) // Let the workers finish their work
close(ch) // Close the channel when done
}