Go 无限循环

无限循环的一个常见的应用场合是用在 goroutine 中,只要主程序不退出,此goroutine 就一直在在后台执行(running in the background),例如下面的logger goroutine:

main.go

package main
import (
	"bufio"
	"fmt"
	"myapp/mylogger"
	"os"
	"time"
)

func main() {
    
    
	reader := bufio.NewReader(os.Stdin)
	ch := make(chan string)		
	go mylogger.ListenForLog(ch)
	fmt.Println("Enter something")

	for i := 0; i < 5; i++ {
    
    
		fmt.Print("->")
		input, _ := reader.ReadString('\n')
		ch <- input
		// Sleep a second
		time.Sleep(time.Second)
	}
}

mylogger.go

package mylogger
import "log"

func ListenForLog(ch chan string) {
    
    
	// infinite loop that never exits
	for {
    
    
		msg := <-ch
		log.Println(msg)
	}
}

猜你喜欢

转载自blog.csdn.net/ftell/article/details/123538154