初级会员
  • 第 52254 位会员
  • yaxiaomu
  • 2020-04-28 10:17:48
  • Offline
  • 20 45

最近分享的资源

    暂无

最近发布的项目

    暂无

最近的评论

  • windows defender 也需要关掉
  • #2 @euibieur894 老哥,我这不是map,是chan
  • 把上述代码整体放在一个goroutine就可以,为啥呢。 ```golang package main import ( "fmt" "sync" "time" ) func main() { go demo1VN() time.Sleep(2*time.Second) fmt.Println("main done") } func demo1VN() { wg := &sync.WaitGroup{} ch := make(chan int, 100) send := func() { for i := 0; i < 100; i++ { ch <- i } //不开启close,如何不死锁? //close(ch) } recv := func(id int) { defer wg.Done() for i := range ch { fmt.Printf("cusumerV1 #%d get %d\n", id, i) } fmt.Printf(" >>>>>>consumerV1 #%d exit,\n", id) for { if i, ok := <-ch; ok { fmt.Printf("cusumerV2 #%d get %d,closed is %v\n", id, i, ok) } else { fmt.Printf(" >>>>>>consumerV2 #%d exit,closed is %v\n", id, ok) return } } } wg.Add(3) go recv(0) go recv(1) go recv(2) go send() wg.Wait() fmt.Println("all done") } ```
  • ### 自问自答二波 ``` package main import ( "fmt" "sync" "time" ) func main() { c := make(chan string) var wg sync.WaitGroup wg.Add(2) go func() { c <- "world" defer wg.Done() }() go func() { defer wg.Done() time.Sleep(1 * time.Second) fmt.Println("hello " + <-c) }() wg.Wait() } ```
  • ### 自问自答一波 ``` package main import ( "fmt" "sync" ) func main() { var ( c chan string sth string sy chan bool wg sync.WaitGroup ) c = make(chan string) sy = make(chan bool) wg.Add(2) go func() { sth = "hello\n" // 到这里sth已经赋值,需要阻塞从c中取数据,因为需要先赋值后打印打印sth【hello】, sy <- true //sy通道消息被接收后,然后像c通道写入,然后这里打印world fmt.Println(<-c) wg.Done() }() go func() { <-sy //赋值sth后 hello后打印h然后把world写入到c channel fmt.Printf(sth) c <- "world" wg.Done() }() wg.Wait() } ```