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.
Coroutine
characteristic
- 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 {
fmt.Println(i)
}
}(i)
}
time.Sleep(time.Millisecond)
}
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
summary
The above is a detailed introduction of goroutine in go language learning. I hope it will help you!