首页 > 其他分享 >channel

channel

时间:2022-08-30 12:55:24浏览次数:40  
标签:缓冲 fmt func go main channel

channel有缓冲与无缓冲同步问题

image-20220830121700980

image-20220830123036108

package main

import (
   "fmt"
   "time"
)

func main() {
   c := make(chan int, 3) //带有缓冲的channel

   fmt.Println("len(c) = ", len(c), ", cap(c)", cap(c))

   go func() {
      defer fmt.Println("子go程结束")

      for i := 0; i < 4; i++ {
         c <- i
         fmt.Println("子go程正在运行, 发送的元素=", i, " len(c)=", len(c), ", cap(c)=", cap(c))
      }
   }()
   time.Sleep(2 * time.Second)
   for i := 0; i < 4; i++ {
      num := <-c //从c中接收数据,并赋值给num
      fmt.Println("num = ", num)
   }
   fmt.Println("main 结束")
}

关闭channel

image-20220830123149878

package main

import "fmt"

func main() {
   c := make(chan int)

   go func() {
      for i := 0; i < 5; i++ {
         c <- i
         //close可以关闭一个channel
         close(c)
      }
   }()
   
   for {
      //ok如果为true表示channel没有关闭,如果为false表示channel已经关闭
      if data, ok := <-c; ok {
         fmt.Println(data)
      } else {
         break
      }
   }

   fmt.Println("Main Finished..")
}

标签:缓冲,fmt,func,go,main,channel
From: https://www.cnblogs.com/suehoo/p/16638896.html

相关文章

  • channel定义与使用
    channel定义与使用packagemainimport"fmt"funcmain(){//定义一个channelc:=make(chanint)gofunc(){deferfmt.Println("goroutine结......
  • 常用Channel
    KafkaChannel生产者a1.channels.c1.type=org.apache.flume.channel.kafka.KafkaChannela1.channels.c1.kafka.bootstrap.servers=hadoop102:9092,hadoop103:9092,......
  • go语言并发-02channel
    go语言通道channel如果说goroutine是Go语言程序的并发体的话,那么channels就是它们之间的通信机制。一个channels是一个通信机制,它可以让一个goroutine通过它给......
  • go 语言 channel for select
    示例demo55packagemainimport("fmt""time")funcmain(){intChan:=make(chanint,10)//初始化intchan通道长度10int......
  • netty源码分析之AbstractNioByteChannel.NioByteUnsafe.read()
    1@Override2publicfinalvoidread(){3finalChannelConfigconfig=config();4if(shouldBreakReadReady(conf......
  • 10.java NIO核心2:通道(Channel)
    publicinterfaceChannelextendClonseable{}. 写案例:@Testpublicvoidwrite(){try{//1.字节输出流到目标文件......
  • Let's Go系列---channel的用法及原理
    基本语法创建channelch1:=make(chanstruct{})ch2:=make(chanint,10)读写channel从channel中读取数据叫做recv;向channel写数据叫做send。//发送数据到channel......
  • 新建db_prop_channel库,执行以下语句
    数据库名称:db_prop_channel表名中文名说明Req_tgkh_dbf投顾开户请求表对应中登请求协议Req_tgkh_tmp_zwj投顾开户请求主文件表Rep_tgkh_dbf投顾开户......