这个hello,world怎么写 channel

yaxiaomu · · 2251 次点击
### 自问自答二波 ``` 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() } ```
#2
更多评论
### 自问自答一波 ``` 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() } ```
#1
坐次沙发,哈哈!
#3