go coroutine (Goroutines)

What Go coroutine that?

Go coroutine function or method is run concurrently with other functions or methods. Go coroutines can be viewed as a lightweight thread. Compared with thread, create a Go coroutine cost very little. So Go applications often see thousands of Go coroutine to run concurrently.

Go coroutine compared to the advantages of thread

  • For comparison thread, Go coroutine very low cost. Stack size is only several kb, and may be increased or decreased depending on the application requirements. The thread must specify the size of the stack, the stack is fixed.
  • Go coroutine will re-use a smaller number of OS threads (Multiplex). Even if there are thousands of Go coroutine program, it may be only a thread. If the thread is blocking a Go Association process occurs (for example, waiting for user input), then the system will then create an OS thread, and the rest Go coroutines are moving to the new OS thread. All of this at runtime, as programmers, we are not directly confronted with these intricate details, but there is a simple API to handle concurrency.
  • Go coroutine using a channel (Channel) communication. Channel for preventing the occurrence of race conditions (Race Condition) When a plurality coroutine access to shared memory. It can be seen as a channel of communication between the pipe Go coroutine. We will discuss in detail in the next tutorial channel.

How to Start a Go coroutine?

When you call a function or method, preceded by the keyword  go, you can make a new Go coroutine to run concurrently.

Let's create a Go coroutine it.

main Package 

Import ( 
    " FMT " 
) 

FUNC Hello () { 
    fmt.Println ( " the Hello World goroutines " ) 
} 
FUNC main () { 
    Go Hello () 
    // start a coroutine, coroutine call returns immediately, the program to the next line, because the end of the main coroutine, the program terminates, the other coroutine will terminate
    // the time.sleep (1 * time.Second) so we need to add this line of code to reflect the concurrent 
    fmt.Println ( " main function " ) 
}

This is the coroutine, to write very simple!

Guess you like

Origin www.cnblogs.com/tigerzhouv587/p/11491787.html