首页 > 其他 > 详细

Golang 细节

时间:2020-03-12 10:07:39      阅读:65      评论:0      收藏:0      [点我收藏+]

 

func main() {
	f, err := os.OpenFile("debug.log", os.O_RDWR, 0666)
	if err != nil {
		panic(err)
	}

	go func() {
		defer f.Write([]byte("2"))
		for {
			f.Write([]byte("1"))
			time.Sleep(time.Second)
		}
	}()

	<-time.Tick(5 * time.Second)
}

  

>11111

  

1.主函数退出后,所有由主函数创建的携程都会结束

2.主函数退出携程内的defer不一定会执行

 

func main() {
	messages := make(chan int, 10)
	done := make(chan bool)

	defer close(messages)
	// consumer
	go func() {
		ticker := time.NewTicker(1 * time.Second)
		for _ = range ticker.C {
			select {
			case what := <-done:
				fmt.Println(what)
				fmt.Println("child process interrupt...")
				return
			default:
				fmt.Printf("send message: %d\n", <-messages)
			}
		}
	}()

	// producer
	for i := 0; i < 10; i++ {
		messages <- i
	}
	time.Sleep(5 * time.Second)
	close(done)
	time.Sleep(1 * time.Second)
	fmt.Println("main process exit!")
}

  

  

>>
send message: 0
send message: 1
send message: 2
send message: 3
false
child process interrupt...
main process exit!

  

Golang 细节

原文:https://www.cnblogs.com/8000cabbage/p/12467009.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!