search
HomeBackend DevelopmentGolangA preliminary exploration of Goroutine and channel in Go language

This article will give you a preliminary understanding of Goroutine and channel in the Go language. I hope it will be helpful to you!

A preliminary exploration of Goroutine and channel in Go language

The implementation of the CSP concurrency model of the Go language contains two main components: one is Goroutine and the other ischannel. This article will introduce their basic usage and precautions.

Goroutine

Goroutine is the basic execution unit of the Go application. It is a lightweight user-level thread , the bottom layer is concurrency achieved through coroutine (coroutine). As we all know, a coroutine is a user thread running in user mode, so Goroutine is also scheduled when the Go program is running.

Basic usage

Syntax: go function/method

You can create a ## through go keyword function/method #Goroutine.

Code example:

import (
   "fmt"
   "time"
)

func printGo() {
   fmt.Println("具名函数")
}

type G struct {
}

func (g G) g() {
   fmt.Println("方法")
}

func main() {
   // 基于具名函数创建 goroutine
   go printGo()
   // 基于方法创建 goroutine
   g := G{}
   go g.g()
   // 基于匿名函数创建 goroutine
   go func() {
      fmt.Println("匿名函数")
   }()
   // 基于闭包创建 goroutine
   i := 0
   go func() {
      i++
      fmt.Println("闭包")
   }()
   time.Sleep(time.Second) // 避免 main goroutine 结束后,其创建的 goroutine 来不及运行,因此在此休眠 1 秒
}

Execution result:

闭包
具名函数
方法
匿名函数

When multiple

Goroutine exist, their execution order is not fixed. Therefore, the results will be different every time you print.

As can be seen from the code, through the

go keyword, we can create goroutine based on the named function / method, also goroutine can be created based on anonymous functions/closures.

So how does

Goroutine exit? Under normal circumstances, as long as the execution of the Goroutine function ends or the execution returns, it means the exit of Goroutine. If Goroutine's function or method has a return value, it will be ignored when Goroutine exits.

channel

channel plays an important role in the Go concurrency model. It can be used to implement communication between Goroutine, and can also be used to implement synchronization between Goroutine.

Basic operations of channel

#channel is a composite data type. When declaring, you need to specify the elements in channel type.

Declaration syntax: var ch chan string

Declare a

channel whose element type is string through the above code. Only elements of type string can be stored. channel is a reference type and must be initialized to write data. It is initialized by make.

import (
   "fmt"
)

func main() {
   var ch chan string
   ch = make(chan string, 1)
   // 打印 chan 的地址
   fmt.Println(ch)
   // 向 ch 发送 "Go" 数据
   ch <- "Go"
   // 从 ch 中接收数据
   s := <-ch
   fmt.Println(s) // Go
}

Through

ch , you can send data to the channel variable ch, via x := Data can be received from the channel variable ch.

Buffered channel and unbuffered channel

If the capacity is not specified when initializing the

channel, an unbuffered # will be created. ##channel: <pre class='brush:php;toolbar:false;'>ch := make(chan string)</pre>The sending and receiving operations of the unbuffered

channel

are synchronous. After the send operation is performed, the corresponding Goroutine will block. , until there is another Goroutine to perform the receive operation, and vice versa. What will happen if the send operation and execution operation are placed under the same Goroutine? Take a look at the following code: <pre class='brush:php;toolbar:false;'>import ( &quot;fmt&quot; ) func main() { ch := make(chan int) // 发送数据 ch &lt;- 1 // fatal error: all goroutines are asleep - deadlock! // 接收数据 n := &lt;-ch fmt.Println(n) }</pre> After the program is run, you will get

fatal error

at ch , prompting all <code>Goroutine In a dormant state, it is deadlocked. To avoid this situation, we need to execute the sending and receiving operations of channel in different Goroutine. <pre class='brush:php;toolbar:false;'>import ( &quot;fmt&quot; ) func main() { ch := make(chan int) go func() { // 发送数据 ch &lt;- 1 }() // 接收数据 n := &lt;-ch fmt.Println(n) // 1 }</pre> It can be concluded from the above example: the sending and receiving operations of unbuffered

channel

must be carried out in two different Goroutine, otherwise it will Occurrencedeadlock image.

If the capacity is specified, a buffered
channel

is created: <pre class='brush:php;toolbar:false;'>ch := make(chan string, 5)</pre>Buffered

channel

and unbuffered chennel is different. When performing a send operation, as long as the buffer of channel is not full, Goroutine will not hang until the buffer is full. channel Performing a send operation will cause Goroutine to hang. Code example: <pre class='brush:php;toolbar:false;'>func main() { ch := make(chan int, 1) // 发送数据 ch &lt;- 1 ch &lt;- 2 // fatal error: all goroutines are asleep - deadlock! }</pre>

Declare the send-only type and receive-only type of channel

  • channel# that can both send and receive

    ##

    ch := make(chan int, 1)
    The channel

    variable is obtained through the above code, and we can perform sending and receiving operations on it.

    Only receiving
  • channel
  • ch := make(<-chan int, 1)
    The channel

    variable is obtained through the above code, we can only receive it .

    Only sent
  • channel
  • ch := make(chan<- int, 1)
    The channel

    variable is obtained through the above code, we can only send it .

通常只发送 channel 类型和只接收 channel 类型,会被用作函数的参数类型或返回值:

func send(ch chan<- int) {
   ch <- 1
}

func recv(ch <-chan int) {
   <-ch
}

channel 的关闭

通过内置函  close(c chan,可以对 <code>channel 进行关闭。

  • 在发送端关闭 channel

    channel 关闭之后,将不能对 channel 执行发送操作,否则会发生 panic,提示 channel 已关闭。

    func main() {
       ch := make(chan int, 5)
       ch <- 1
       close(ch)
       ch <- 2 // panic: send on closed channel
    }
  • 管道 channel 之后,依旧可以对 channel 执行接收操作,如果存在缓冲区的情况下,将会读取缓冲区的数据,如果缓冲区为空,则获取到的值为 channel 对应类型的零值。

    import "fmt"
    
    func main() {
       ch := make(chan int, 5)
       ch <- 1
       close(ch)
       fmt.Println(<-ch) // 1
       n, ok := <-ch
       fmt.Println(n)  // 0
       fmt.Println(ok) // false
    }
  • 如果通过 for-range 遍历 channel 时,中途关闭 channel 则会导致 for-range 循环结束。

小结

本文首先介绍了 Goroutine的创建方式以及其退出的时机是什么。

其次介绍了如何创建 channel 类型变量的有缓冲与无缓冲的创建方式。需要注意的是,无缓冲的 channel 发送与接收操作,需要在两个不同的 Goroutine 中执行,否则会发送 error

接下来介绍如何定义只发送和只接收的 channel 类型。通常只发送 channel 类型和只接收 channel 类型,会被用作函数的参数类型或返回值。

最后介绍了如何关闭 channel,以及关闭之后的一些注意事项。

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

The above is the detailed content of A preliminary exploration of Goroutine and channel in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software