标签:def 打印 range 数据 阻塞 sleep out efault sql
题记:
请使用两个协程交替输出AaBbCcDdEeFf.....,要求协程1只能输出ABC......,协程2只能输出abc.....
实现逻辑(当一个协程打印了之后,发一个信号给到done,然后另一个阻塞的协程就接收到信号继续打印,一次类推)
自己实现了个代码,测试没问题,不知道是不是最优
代码如下:
package main import ( "fmt" "sync" "time" ) //两个goroutine,一个打印A,另一个打印a, 顺序打印AaBbCcDd..... var wg sync.WaitGroup func worker1(ch chan struct{},data chan string) { fmt.Println("worker 1") defer wg.Done() for{ select { case <-ch: tmp :=<- data time.Sleep(time.Second*1) fmt.Println("big:",tmp) ch <- struct{}{} //发送信号 default: } } } func worker2(ch chan struct{},data chan string) { fmt.Println("worker 2") defer wg.Done() ch<- struct{}{} // 先发送信号给协程1 for{ select { case <-ch: tmp :=<- data time.Sleep(time.Second*1) fmt.Println("small:",tmp) ch <- struct{}{} //发送信号 default: } } } func main() { done := make(chan struct{}) dataChan :=make(chan string) wg.Add(1) go func() { defer wg.Done() s1 := []string{"A","a","B","b","C","c","D","d","E","e","F","f"} for _,v := range s1 { dataChan <- v //一个阻塞的channel,数据源 } //for i :=0;i<100;i++{ // dataChan <- strconv.Itoa(i)+"_test" //} }() wg.Add(2) go worker1(done,dataChan) go worker2(done,dataChan) wg.Wait() }
标签:def 打印 range 数据 阻塞 sleep out efault sql
原文地址:https://www.cnblogs.com/pebblecome/p/14323824.html