• Golang 细节


    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
    ", <-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!
    

      

  • 相关阅读:
    四级英语day9
    123
    像程序员一样思考
    Kali
    OS X
    Effective Java
    DHU ACM OJ
    Ambari
    Hadoop
    Hadoop2
  • 原文地址:https://www.cnblogs.com/8000cabbage/p/12467009.html
Copyright © 2020-2023  润新知