Maison> développement back-end> Golang> le corps du texte

golang怎么将通道关闭

青灯夜游
Libérer: 2023-01-11 11:12:23
original
2596 Les gens l'ont consulté

在golang中,可以使用close()函数来关闭通道,语法“close(msg_chan)”。 通道(chan)是一种系统资源,因此在不需要使用chan 时,需要使用内置函数close来手动关闭管道。注如果向一个已经关闭的管道发送数据,那么程序会pannic。

golang怎么将通道关闭

本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。

Go 语言 中的 通道(chan) 也是一种系统资源,因此,我们不需要使用 chan 时,需要手动关闭管道。关闭管道,需要使用系统内置的 close 函数。

close()是一个内置函数,并设置一个标识,表示不再有任何值将发送到该通道。

close(msg_chan)
Copier après la connexion
参数 描述
msg_chan 需要关闭的管道。

您也可以使用for范围循环关闭通道。在这里,接收器goroutine可以借助给定的语法检查通道是打开还是关闭:

ele, ok:= <- Mychannel
Copier après la connexion

在此,如果ok的值为true,则表示通道已打开,因此可以执行读取操作。并且,如果的值为false,则表示该通道已关闭,因此将不执行读取操作。

说明

  • 我们在使用 变量 接受管道返回的数据后,第二个 bool 类型的返回值表示管道是否关闭,如果为 false,则表明管道已经关闭。

关闭通道的示例

//Go程序说明如何 //关闭使用的通道 //range循环和关闭函数 package main import "fmt" func myfun(mychnl chan string) { for v := 0; v < 4; v++ { mychnl <- "nhooo" } close(mychnl) } func main() { //创建通道 c := make(chan string) // 使用 Goroutine go myfun(c) //当ok的值为为true时,表示通道已打开,可以发送或接收数据 //当ok的值设置为false时,表示通道已关闭 for { res, ok := <-c if ok == false { fmt.Println("通道关闭 ", ok) break } fmt.Println("通道打开 ", res, ok) } }
Copier après la connexion

1.png

向已经关闭的管道发送数据,程序会 pannic

package main import "fmt" func main() { fmt.Println("嗨客网(www.haicoder.net)") ch := make(chan string, 5) ch <- "Hello" ch <- "HaiCoder" ch <- "Python" close(ch) ch <- "Close" }
Copier après la connexion

2.png

关闭管道之后,我们再次使用关闭的管道发送了一条 “Close” 消息,运行程序后,我们看到程序 pannic,即,关闭的管道不可以再次发送数据,否则,程序会 pannic。

【相关推荐:Go视频教程编程教学

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!