• go channel 退出通道


    退出管道

    package main
    
    import (
    	"fmt"
    	"time"
    )
    // 每隔 1s 向通道 发送一条信息
    func Sender(c chan string)  {
    	t := time.NewTicker(1 *time.Second)
    
    	for {
    		c <- "i am sending a message"
    		<-t.C
    	}
    
    }
    
    
    func main()  {
    	// 创建一个字符串通道
    	message := make(chan string)
    	// 创建一个 bool 类型通道 用于退出for 循环
    	stop :=make(chan bool)
    
    	//  新起一个 Goroutine  调用Sender 函数,每隔1s 向message通道发送数据
    	go Sender(message)
    
    
    	// 新起一个 Goroutine 5 秒之后,向 for 循环 管道case 发送一条消息
    	go func() {
    		time.Sleep(time.Second*5)
    		fmt.Println("time is up")
    		stop <- true
    	}()
    
    
    	// 通过for 循环 收到消息后立即打印它
    	for {
    		select {
    		// 通过创建一个通道,可让程序向这个通道发一条消息, stop 管道 收到 消息 就return 从而结束for 循环
    		case <- stop:
    			return
    
    		case msg := <- message:
    			fmt.Println(msg)
    
    		}
    
    	}
    
    }
    

      

  • 相关阅读:
    HashMap 链表插入方式 → 头插为何改成尾插 ?
    MySQL 日志之 binlog 格式 → 关于 MySQL 默认隔离级别的探讨
    Eclipse
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
  • 原文地址:https://www.cnblogs.com/zexin88/p/14957985.html
Copyright © 2020-2023  润新知