A detailed explanation of Go language learning

  • 2020-10-07 18:44:39
  • OfStack

What is goroutine?

Goroutine is a lightweight abstraction built on threads. It allows us to execute multiple functions or methods in parallel in the same address space at a very low cost. It is much less expensive to create and destroy than a thread, and its scheduling is thread independent. Creating an goroutine in golang is simple, using 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 looks like this:

[

My first goroutinemain function

]

If you remove Sleep, the output will be:

main function

This is because, like thread 1, the main function of golang (which actually runs in one goroutine) does not wait for the other goroutine to end. If the main goroutine ends, all other goroutine ends.

Here is goroutine for Go language learning.

Coroutines Coroutine

The characteristics of

Lightweight "threads" Non-preemptive multitasking, in which the coroutine voluntarily relinquished control Compiler/interpreter/VMS level multi-tasking, non-operating system Multiple coroutines can execute on one or more threads

The go keyword opens 1 coroutine


func main() {
  for i := 0; i < 10; i++ {
    go func(i int) {
      for {
        fmt.Println(i)
      }
    }(i)
  }
  time.Sleep(time.Millisecond)
}

Possible switching points of goroutine (transfer of control)

I/O,select channel Waiting for the lock Function calls (sometimes) routime.Goshed() Just a reference, no guarantee of switching, no guarantee of not switching elsewhere

conclusion

Above is the site to introduce Go language learning goroutine detailed explanation, I hope to help you!


Related articles: