golang面试总结(持续更新)
package main
import "fmt"
func Producer(ch chan int) {
for i := 1; i <= 100; i++ {
ch <- i
}
close(ch)
}
func Consumer(id int, ch chan int, done chan bool) {
for {
value, ok := <-ch
if ok {
fmt.Printf("id: %d value: %dn", id, value)
} else {
fmt.Printf("id: %d, closedn", id)
break
}
}
done <- true
}
func main() {
ch := make(chan int, 3)
consumerNum := 2
done := make(chan bool, consumerNum)
for i:=1;i<=consumerNum;i++ {
go Consumer(i, ch, done)
}
go Producer(ch)
for i:=1;i<=consumerNum;i++{
<-done
}
}
//以下是两个消费者:
package main
import "fmt"
func Producer(ch chan int) {
for i := 1; i <= 100; i++ {
ch <- i
}
close(ch)
}
func Consumer(id int, ch chan int, done chan bool) {
for i := 0; i < 50; i++ {
fmt.Printf("id: %d receive: %dn", id, <-ch)
}
done <- true
}
func main() {
ch := make(chan int)
consumerNum := 2
done := make(chan bool, consumerNum)
for i := 1; i <= consumerNum; i++ {
go Consumer(i, ch, done)
}
go Producer(ch)
for i := 1; i <= consumerNum; i++ {
<-done
}
}