赞
踩
有一道这样的面试题目:
写代码实现两个 goroutine,其中一个产生随机数并写入到 go channel 中,另外一个从 channel 中读取数字并打印到标准输出。最终输出五个随机数。
解决思路:
package main import ( "fmt" "math/rand" "sync" ) func main() { output := make(chan int) var wg sync.WaitGroup randFunc := func() { defer wg.Done() for i := 0; i < 5; i++ { output <- rand.Intn(10) } close(output) } wg.Add(2) go randFunc() go func() { defer wg.Done() for i := range output { fmt.Println(i) } }() wg.Wait() }
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。