首页 > 其他分享 >[ Go] GoRoutines and Channels

[ Go] GoRoutines and Channels

时间:2024-02-06 16:23:51浏览次数:26  
标签:great printMessage Channels go Go main Rust GoRoutines

A goroutine is the Go way of suing threads, we open a goroutine just by invoking any function with a go prefix.

go functionCall()

Goroutines can communicate through channels, an special type of variable, a channel contains a value of any kind, a routine can define a value for a channel and other routine can wait for that value.

Channels can be buffered or not.

// define a chan type is string
var foo chan string
// constructor make
bar := make(chan string)
// write into channel
bar <- "hello"
// other can read message
message := <- bar

 

Goroutines example:

// Without go routines
package main

import (
	"fmt"
	"time"
)

func printMessage(text string) {
	for i := 0; i < 3; i++ {
		fmt.Println(text)
		time.Sleep(300 * time.Millisecond)
	}
}

func main() {
	printMessage("Go is great!")
	printMessage("Rust is great!")
}

Output:

/*
Go is great!
Go is great!
Go is great!
Rust is great!
Rust is great!
Rust is great!
/*

Without Goroutines

func main() {
	go printMessage("Go is great!")
	printMessage("Rust is great!")
}

Output:

/*
Rust is great!
Go is great!
Go is great!
Rust is great!
Rust is great!
Go is great!
/*

 

Notice that you cannot do 

func main() {
	go printMessage("Go is great!")
	go printMessage("Rust is great!")
}

No output for this code, because the main goroutines ends when main function exit, which also ends sub goroutines.

 

Channel

package main

import (
	"fmt"
	"time"
)

func printMessage(text string, chanMsg chan string) {
	for i := 0; i < 3; i++ {
		fmt.Println(text)
		time.Sleep(300 * time.Millisecond)
	}
	chanMsg <- "Done!"
}

func main() {
	chanMsg := make(chan string)
	go printMessage("Go is great!", chanMsg)
	// Wait channel message then print
	response := <-chanMsg
	fmt.Println(response)
}

/*
Go is great!
Go is great!
Go is great!
DONE!
*/

 

标签:great,printMessage,Channels,go,Go,main,Rust,GoRoutines
From: https://www.cnblogs.com/Answer1215/p/18009906

相关文章

  • Typora PicGo SM
    TyporaPicGoSM.MS图床设置在程序猿的世界中,只有输出,不断输出才能成为自己在工作中的源头活水,因此在工作中,不断的记录遇到的问题和解决的思路和过程,对于锤炼思考有着十分重要的过程。文章写作作为文笔输出的重要部分,因此在工作生涯中扮演者举足轻重的作用。本文介绍了使用Typora......
  • GO镜像
    UNIX#启用GoModules功能goenv-wGO111MODULE=on#配置GOPROXY环境变量,以下三选一#1.七牛CDNgoenv-wGOPROXY=https://goproxy.cn,direct#2.阿里云goenv-wGOPROXY=https://mirrors.aliyun.com/goproxy/,direct#3.官方goenv-wGOPROXY=https:......
  • 解决golang依赖库被删库问题
    调用的开源库引用了github个人仓库,如果作者删除了仓库或者改成私人仓库,那么gomodtidy就会失败以github.com/mitchellh/osext为例,作者因为某些原因删除了仓库,并给出了替代的官方仓库github.com/kardianos/osext使用replace命令gomodedit-replace[oldgitpackage]@[versi......
  • Golang Grpc-Gateway生成-buf版
    官网有个工具buf可以自动生成https://github.com/bufbuild/buf/releases按照自己的平台下载对应的文件,并把可执行文件加入到环境变量下proto同级目录下新增buf.gen.yaml或者执行bufmodinit,buf默认会扫描所有文件夹的*.proto,所以我在同级目录下创建version:v1plugins:-......
  • Golang Grpc-Gateway生成-基础版
    时间久了不用就会忘记指令,这里做个笔记创建一个文件//+buildtoolspackagetoolsimport(_"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway"_"github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2"_"google.gol......
  • [Go] Defer keyword
    defermakesuretheoperationwillbeexecutedattheendofafunction.funcloadChampions()([]champion,error){ file,err:=os.Open("tft_champions.json") iferr!=nil{ returnnil,err } deferfile.Close() varchampions[]champion......
  • [Go] defer & recover
    PanicrecoveryisamechanisminGothatallowsaprogramtohandleunexpectederrors(panics)gracefully. packagemainimport( "fmt")funcmayPanic(){ //Thisfunctionsimulatesasituationthatcausesapanic. //Forexample,adivisi......
  • [Go - slice] Remove Elements from a slice in Go
    Gohasaspecialindexingsyntaxthatformsthebasisofremovingoneormoreelementsfromaslice.Iwillteachyouthissyntaxandshowyouitsvariousforms.Baseduponthat,I'llshowyouhowtoremoveasingleelementfromaslice.However,you......
  • 2月摸鱼计划03 从并发编程本质了解Go高性能的本质
    1.0从并发编程本质了解Go高性能的本质1.1Goroutine协程可以理解为轻量级线程;Go更适合高并发场景原因之一:Go语言一次可以创建上万协成;“快速”:开多个协成打印。gofunc():在函数前加go代表创建协程;time.Sleep():协程阻塞,使主协程在子协程结束前阻塞不退出;乱序输出说......
  • client-go http trace分析耗时
    klog.InitFlags(nil)flag.Parse()deferklog.Flush()cfg,err:=clientcmd.BuildConfigFromFlags("","/root/.kube/config")iferr!=nil{ klog.Fatalf("Errorbuildingkubeconfig:%s",err.Error())}kubeClient,err:=kubern......