(四十 一) golang - goroutine

First of all have to understand:

  • process
  • Thread
  • Complicated by
  • parallel

Go and Go coroutine main thread:

Main thread: the equivalent process; directly on cpu, heavyweight, physical state;

Coroutine: equivalent lightweight thread; by the primary co Chengkai Qi, logic state;

Go coroutine features:

  • Independent stack space
  • Sharing program file unit
  • Scheduling control by the user
  • Coroutine is lightweight thread

for example:

package main

import (
    "fmt"
    "strconv"
    "time"
)

func test() {
    for i := 0; i < 20; i++ {
        fmt.Println("test() hello world" + strconv.Itoa(i))
        time.Sleep(time.Second)
    }
}

func main() {
    go test()
    for i := 0; i < 10; i++ {
        fmt.Println("main() hello world" + strconv.Itoa(i))
        time.Sleep(time.Second)
    }
    fmt.Println("finish")
}

The main test for and run in for the same time, when the main coroutine main printed 10 times, regardless of the test coroutine in print several times, test coroutine will end off.

Coroutine main and coroutine relationship:

 

 MPG mode:

  • M: main coroutine, physical coroutine;
  • P: coroutine context requires;
  • G: coroutine

 

Description:

(1) There are three current program M, if M three runs in the same cpu, is concurrently; running on different cpu, it is parallel;

(2) the representative gray coroutine queue;

(3) go coroutine is lightweight thread, logic state;

(4) other multithreaded programs, often kernel mode, heavier-weight;

Scheduling model:

 

(1) is divided into two portions view;

(2) the original master M0 coroutine G0 coroutine is executed, and another three coroutine is waiting in the queue;

(3) If the G0 Coroutine obstruction, such as reading and other documents or databases; (that is to say do not know when it can be done)

(4) at this time will create a coroutine master M1 (M1 may be removed from the existing thread pool), and waits for the next three coroutine linked to M1 begins execution, the G0 M0 is the main thread still continues;

(5) Wait until G0 is not blocked, M0 will be placed to idle the main thread to continue, while G0 will be awakened;

 Set to use several cpu:

Guess you like

Origin www.cnblogs.com/xiximayou/p/11950739.html