Go series of tutorials - 21. Go coroutine

Welcome to  Golang tutorial series on the 21.

In the previous tutorial, we discuss concurrency, and the difference between concurrent and parallel. This tutorial will introduce in the Go language, how to implement concurrent use Go coroutines (Goroutine).

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.

package main

import (
    "fmt"
) func hello() { fmt.Println("Hello world goroutine") } func main() { go hello() fmt.Println("main function") } 

 

In line 11, go hello() we launched a new Go coroutine. Now  hello() function and  main() function concurrently. Main function running on a specific coroutine Go, Go it as a main coroutine (Main Goroutine).

Run the program, you will be amazed!

The program will output text  main function. We started Go coroutine and what are the problems? To understand all this, we need to understand the nature of two main Go coroutine.

  • When you start a new coroutine, coroutine call will return immediately. With different functions, program control not going to wait for Go coroutine is finished. Go after calling coroutine, program control returns immediately to the next line of code, ignoring any return value of the coroutine.
  • If you want to run another coroutine Go, Go main coroutine must continue running. If the main Go coroutine terminated, the program is terminated, then the other Go coroutine will not continue to run.

Now you should be able to understand why our Go coroutine not running it. In line 11 calls  go hello() after the program control without waiting for  hello the end of the coroutine to return immediately to the next line of code, print  main function. Since then no other executable code, Go main coroutine terminated, so  hello coroutine no chance to run.

We now fix the problem.

package main

import (  
    "fmt"
    "time" ) func hello() { fmt.Println("Hello world goroutine") } func main() { go hello() time.Sleep(1 * time.Second) fmt.Println("main function") } 

 

In line 13 above program, we call the time function of the bag  Sleep, the function will carry out its dormant Go coroutine. Here, we make the main coroutine Go to sleep one second. Therefore, before the main coroutine terminated calls  go hello() have enough time to executed. The program first print  Hello world goroutine, after waiting for one second, followed by printing  main function.

Go in the main coroutine dormant, waiting for the other coroutine is finished, this method is only used to understand tips on how to Go coroutines work. Channel may be used prior to the other end of the coroutine execution, the main blocking Go coroutine. We will discuss in the next tutorial channel.

Go to start multiple coroutines

To better understand the coroutine Go, we'll write a program to start multiple Go coroutine.

package main

import (  
    "fmt"
    "time" ) func numbers() { for i := 1; i <= 5; i++ { time.Sleep(250 * time.Millisecond) fmt.Printf("%d ", i) } } func alphabets() { for i := 'a'; i <= 'e'; i++ { time.Sleep(400 * time.Millisecond) fmt.Printf("%c ", i) } } func main() { go numbers() go alphabets() time.Sleep(3000 * time.Millisecond) fmt.Println("main terminated") } 

 

In line 21 the above procedure and the line 22, to start the two Go coroutine. Now, the two co-routines to run concurrently. numbers Coroutine first 250 microseconds to sleep, then print  1, then sleep again, printing  2, and so on, until the printing  5 is finished. alphabete Similarly coroutine from print  a to  eletters, and each has a sleep time 400 microseconds. Go main coroutine started  numbers and  alphabete two Go coroutine, Sleep 3000 microsecond after the termination of the program.

The program will output:

1 a 2 3 b 4 c 5 d e main terminated

Operation program is shown in FIG. In order to view pictures, open in a new tab.

image

Blue view showing the first  numbers coroutine, second maroon view showing  alphabets coroutine, third green Go view showing a main coroutine, and the last one the above three black FIG coroutine merged, how to indicate that the program is running. At the top of each block, such  0 ms and  250 ms such a string representation of the time (in microseconds). At the bottom of each 1block, 2, , 3 and the like represent the output. Blue boxes represent: 250 ms print out  1, 500 ms print out  2, and so on. Finally, the bottom of the black box value would be  1 a 2 3 b 4 c 5 d e main terminated, which is also the output of the entire program. The above picture is very intuitive, you can use it to understand how the program works.

Go coroutine introduced to this end. wish you happiness.

Guess you like

Origin www.cnblogs.com/fengchuiyizh/p/11349813.html