Golang-goroutine / channel

goroutine-Basic introduction

Process and thread introduction

    

 

 

Schematic diagram of the relationship between programs, processes and threads

    

Concurrency and parallelism

  1) Multi-threaded programs run on a single core, which is concurrent
  2) Multi-threaded programs run on multiple cores, which is parallel
  3) Schematic diagram:

     

    summary:

    

 

 

 

Go coroutine and Go main thread

    Go main thread (some programmers directly call it a thread / can also be understood as a process): A Go thread can have multiple coroutines. You can understand this as a coroutine is a lightweight thread [the compiler does optimization] .

Features of Go coroutines
    1) Independent stack space
    2) Shared program heap space
    3) Scheduling is controlled by the user
    4) Coroutines are lightweight threads

    schematic diagram

      

 

 

   

goroutine-Quick Start
   Case Description
     Please write a program to complete the following functions:
    1) In the main thread (can be understood as a process), start a goroutine, the coroutine outputs "hello, world" every 1 second
    2) In the main The thread also outputs "hello, golang" every second. After outputting 10 times, exit the program.
    3) Require the main thread and goroutine to execute at the same time.
    4) Draw the main thread and coroutine execution flowchart

    

 

 

     The effect of the output shows that the main thread main and the test coroutine are executed simultaneously.

    

 

 

Main thread and coroutine execution flowchart

  

 

 

 

Quick start summary
  1) The main thread is a physical thread that directly acts on the CPU. It is heavyweight and consumes cpu resources very much.
  2) The coroutine started from the main thread is a lightweight thread and is a logical state. The resource consumption is relatively small.
  3) Golang's coroutine mechanism is an important feature, which can easily open tens of thousands of coroutines. The concurrency mechanism of other programming languages ​​is generally thread-based. Too many threads are opened, which consumes a lot of resources. Here, Golang's advantages in concurrency are highlighted.


A
  basic introduction to the MPG model of the goroutine scheduling model

  

 

   MPG mode operation status 1

  

 

   MPG mode operation status 2

  

 

Guess you like

Origin www.cnblogs.com/Essaycode/p/12729240.html