3.9 计算器 使用协程


package main

import (
	"fmt"
	"os"
	"os/signal"
	"time"
)

func main() {

	c := make(chan os.Signal, 1)
	signal.Notify(c)

	ticker := time.NewTicker(time.Second)
	stop := make(chan bool)

	go func() {
		defer func() { stop <- true }()
		for {
			select {
			case <-ticker.C:
				fmt.Println("Tick")
			case <-stop:
				fmt.Println("Goroutine closing")
				return
			}
		}
	}()

	// Block until
	// the signal is received
	<-c
	ticker.Stop()

	// Stop the goroutine
	stop <- true
	// Wait until the
	<-stop
	fmt.Println("Application stopped")
}

/*
Tick
Tick
Tick
Tick
Tick
Tick
Tick
Goroutine closing
Application stopped


*/
posted @ 2018-03-22 00:32  cucy_to  阅读(118)  评论(0)    收藏  举报