Go语言入门经典:通道Channel

1. 相比于Goroutine,通道有何优点?

通道给予了Goroutine与主函数间互相通信的可能,给予一个受控的并发编程环境

2.select语句中的超时时间有何用途?

通过使用超时时间( <- time. After( ) ),使得无法接收到通道消息的select语句,得以结束程序的阻塞,继续执行。

3.如何编写从一个通道那里接收10条消息后退出的程序?

package main

import "fmt"

func main(){
	c := make(chan string)
	go print(c)

	
	for i:= 0; i<10; i++{
		select {
		case msg:=<-c:
			fmt.Println(msg)
		}
	}
}

func print(c chan string){
	for {
	c <- "Hello World!"
	}
}

4.修改介绍Goroutine的第10章的example05.go,使其使用通道。在其中使用一个包含select语句的for循环,并指定超时时间,如果在指定时间内没有收到响应,则直接返回。本章示例代码中的example10.go提供了一种解决方案。

package main

import (
	"fmt"
	"time"
)

func main() {
	c1 := make(chan string)
	c2 := make(chan string)

	go thrill1(c1)
	go thrill2(c2)

	for {
		select {
		case msg1 := <-c1:
			fmt.Println(msg1)
		case msg2 := <-c2:
			fmt.Println(msg2)
		case <-time.After(time.Second * 4):
			fmt.Println("Time is up!")
			return
		}
	}
}

func thrill1(c chan string) {
	time.Sleep(time.Second * 3)
	c <- "This is Channel c1"
}

func thrill2(c chan string) {
	time.Sleep(time.Second * 2)
	c <- "This is channel c2"
}

猜你喜欢

转载自blog.csdn.net/fengqy1996/article/details/124571863