SoFunction
Updated on 2025-03-05

Go language learning goroutine details

What is goroutine?

Goroutine is a lightweight abstraction that builds threads. It allows us to execute multiple functions or methods in parallel in the same address space at very low cost. Compared to threads, its creation and destruction cost much less, and its scheduling is thread-independent. Creating a goroutine in golang is very simple, just use the "go" keyword:

package mainimport ( "fmt" "time")func learning() { ("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.*/ (1 * ) ("main function")}

The output of this code is as follows:

My first goroutinemain function

If you remove Sleep, the output will become:

main function

This is because, like threads, the main function of golang (actually running in one goroutine) does not wait for the other goroutines to end. If the main goroutine is finished, all other goroutines will end.

Let’s take a look at the relevant content of Go language learning goroutine.

Coroutine

Features

  • Lightweight "thread"
  • Non-preemptive multitasking, coroutines actively hand over control rights
  • Multitasking at compiler/interpreter/VM level, non-operating system
  • Multiple coroutines can be executed on one or more threads

Go keyword to open a coroutine

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

possible switching points for goroutine (transfer of control)

  • I/O,select
  • channel
  • Wait for lock
  • Function calls (sometimes)
  • ()
  • It is just a reference, no switching is guaranteed, no switching is guaranteed elsewhere

Summarize

The above is a detailed explanation of goroutine for Go language learning introduced to you by the editor. I hope it will be helpful to everyone!