Go语言协程和无缓冲通道使用

示例代码:

package main

import (
	"fmt"
	"time"
)

func hello(channel_hello chan string) {
	fmt.Println("hello.")
	//确保hello打印输出
	time.Sleep(1*time.Second)
	//发送数据到通道
	channel_hello <- "hello_channel"
	//关闭通道,通知接受者此通道不会再发送数据
	close(channel_hello)
}

func main()  {
	//创建无缓冲通道channel,用于goroutine之间通信
	channel_hello := make(chan string)
	//创建协程goroutine
	go hello(channel_hello)
	status_flag := true
	for status_flag {
		select {
		case chan_receive,chan_status := <- channel_hello:
			if chan_status {
				//从通道接收数据
				fmt.Println("msg receive from channel success:", chan_receive)
			} else {
				//通道被关闭
				status_flag = false
				fmt.Println("chan close success", chan_status)
			}
		default:
		}
	}
	fmt.Println("main end.")
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值