A detailed explanation of goroutine in go language learning


What is goroutine?

Goroutine is a lightweight abstraction built on top of threads. It allows us to execute multiple functions or methods in parallel in the same address space at a very low cost. Compared with thread, the cost of its creation and destruction is much less, and its scheduling is independent of the thread. It is very simple to create a goroutine in golang. You can use the “go” keyword:

package mainimport ( “fmt” “time”)func learning() { fmt.Println(“My first goroutine”)}func main() { go learning() /* we are using time sleep so that the main program does not terminate before the execution of goroutine.*/ time.Sleep(1 * time.Second) fmt.Println(“main function”)}

The output of this code is like this:

My first goroutinemain function

If you remove sleep, the output will become:

main function

This is because, like threads, the main function of golang (which actually runs in a goroutine) does not wait for other goroutines to finish. If the main goroutine ends, all other goroutines will end.

Let’s take a look at goroutine in go language learning.



  • Lightweight “thread”
  • Non preemptive multi task processing, in which coprocessor takes the initiative to hand over control
  • Compiler / interpreter / virtual machine level multitasking, non operating system
  • Multiple coroutines can be executed on one or more threads

Go keyword opens a coroutine

func main() {
  for i := 0; i < 10; i++ {
    go func(i int) {
      for {

Possible switching point of goroutine (transfer of control)

  • I/O,select
  • channel
  • Waiting for lock
  • Function call (sometimes)
  • routime.Goshed()
  • It’s just a reference. It can’t guarantee the switch or not switch in other places


The above is a detailed introduction of goroutine in go language learning. I hope it will help you!

Recommended Today

Windows 10 uses screen keyboard

Link to the original text:http://xiaoheidiannao.com/articles/Screen-Keyboard.html More computer skills can be found at:http://xiaoheidiannao.com/articles/Screen-Keyboard.htmlCheck it out catalog introduce Typing mode Numeric keypad Opening method introduce The screen keyboard comes with windows 10Software, which allows users tomouserealizationkeyboardThe function of. On screen keyboardwindowWill be displayed at the top of the screen, otherSoftwarewindowIf it overlaps with the screen keyboard, it […]