首页 > 其他分享 >go 语言 goroutine通信

go 语言 goroutine通信

时间:2022-08-21 23:00:29浏览次数:49  
标签:intChan goroutine chan 通信 int func go resultChan

示例demo52 package main
import (   "fmt" )
func calc(taskChan chan int, resChan chan int, exitChan chan bool) {   for v := range taskChan {     flag := true     for i := 2; i < v; i++ {       if v%i == 0 {         flag = false         break       }     }     if flag {         //值放到resChan 通道里       resChan <- v     }   }     fmt.Println("exit")     exitChan <- true   }
func main() {   intChan := make(chan int, 1000) //初始化 intchan 通道 长度1000   resultChan := make(chan int, 1000) //初始化 resultChan通道 长度1000   closeChan := make(chan bool, 8)   go func() { //协程方式放进10000个数到intChan通道里     for i := 0; i < 100000; i++ {       intChan <- i     }     close(intChan) //关闭intChan通道   }()
  //启8个协程 运行计算 传入intChan 和resultChan   for i := 0; i < 8; i++ {     go calc(intChan, resultChan, closeChan)   }
  //等待所有计算的goroutine全部退出   go func() {     for i := 0; i < 8; i++ {       <-closeChan     }     close(closeChan) //关闭closeChan通道     close(resultChan) //关闭resultChan通道   }()
  //循环 resultChan遍历数据   for v := range resultChan {     fmt.Println(v)   }
}

标签:intChan,goroutine,chan,通信,int,func,go,resultChan
From: https://www.cnblogs.com/chenweihao/p/16611320.html

相关文章

  • golang语法速记
    Golang语言中存在一个关键字type,type又有两种使用方式,一种是类型别名,一种是类型定义。GoLang1.9后对內建定义类型使用了新的写法:typeNewName=Type这个NewName只是Typ......
  • Golang基础入门
    基础入门1、输出输出,在运行代码时将内容在终端输出。packagemainimport"fmt"funcmain(){fmt.Println("helloword!")}在Go中提供了多种输出的方式......
  • Django 2.0 新特点
    2017年12月2日,Django官方发布了2.0版本,成为多年来的第一次大版本提升,那么2.0对广大Django使用者有哪些变化和需要注意的地方呢?一、Python兼容性Django2.0支持Python3.......
  • useEffect用来监听组件间通信——订阅发布失效
    1.在做这个图书订阅管理系统时,遇到一个这样的业务逻辑:就是这样的逻辑::点击设置---》选择书籍---》点击提交按钮--》轮播图展示这是订阅的代码,没有啥问题,页面挂载的......
  • Golang的IDE的安装
    Golang的IDE的安装Goland是一款由JetBrains公司开发的软件,使用他可以大大提高程序员开发Go代码的效率,因为Goland内部提供了编辑器、调试器和图形用户界面等很多方便的功......
  • golang反射reflect
    1reflect包reflect包实现了运行时反射,允许程序操作任意类型的对象。典型用法是用静态类型interface{}保存一个值,通过调用TypeOf获取其动态类型信息,该函数返回一个Type类......
  • PicGo+GitHub 图床搭建
    前言用GitHub搭建图床,在很久之前我就有了解,但由于市面上有挺多免费的图床,比如我之前一直在用的路过图床,所以一直懒得动手搭建GitHub图床。一直到前两天我在完善博客的相......
  • go 语言 chan读写数据
    示例demo51packagemainimport("fmt""time")funcsendData(chchanint){//把数据写到通道里fori:=0;i<20;i++{......
  • [Google] LeetCode 2013 Detect Squares
    YouaregivenastreamofpointsontheX-Yplane.Designanalgorithmthat:Addsnewpointsfromthestreamintoadatastructure.Duplicatepointsareallow......
  • golang 值类型与引用类型
    转自:https://www.zhihu.com/search?type=content&q=golang%20%20%E5%80%BC%E7%B1%BB%E5%9E%8B%E3%80%81%E5%BC%95%E7%94%A8%E7%B1%BB%E5%9E%8B%E3%80%81%E6%8C%87%E9%92%88......