Go language concurrent Programming (i)

Source: Internet
Author: User
Tags builtin sleep function

The feature of Go language has to mention is the concurrency mechanism, in C language to write very cumbersome and complex concurrent programs in the go language can be very convenient.
These days to write concurrent test scripts, combined with the code and other Daniel's article learned a bit. Write down your own understanding. If there is any mistake, please correct me.

one, concurrency and parallelism

The concurrent programs in Go are mainly implemented by Goroutine and channel.
Here I would like to explain the word "concurrency", the beginning of concurrency as a parallel, always feel that the code is a problem, in fact, this is not the same thing.
Concurrency is: two queues, while accessing a resource in turn. and parallel: Two queues, each of which accesses two resources in turn.
Simply put, concurrency, like a person (CPU) Feeds 2 children (programs), rotates each person to feed a mouthful, the surface of the two children are eating. In parallel, 2 people feed 2 children, and two children eat at the same time.

code example

In the past, when we called multiple threads to print out an ordered number, the thread of the system would be preempted to output, showing a disorderly output. The result of multiple goroutine concurrency is the output of a sequence of sequential numbers followed by a sequence of numbers. Example code:

var quitChanInt=Make(ChanInt)FuncLoop(){For I:=0; I<10; I++{FMT.Printf("%d", I)} quit<-0}FuncMain({//open two goroutine run function loop, The loop function is responsible for printing 10 numbers go loop ( go loop () //ensure Goroutine is executed, the main thread is finished for i := 0; Span class= "token operator" >< 2 I++ {<-quit }               /span>          

Output Result:

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

But the results we used to implement with threads are random, like this:

0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
Ii. How the Goroutine is implemented

In fact, the default go all Goroutines can only run in one thread, and a goroutine is not the equivalent of a thread, the goroutine is to replace the original thread concept into the smallest dispatch unit. (Once the goroutine is run, the thread is searched first, and if it is blocked, it is allocated to the idle thread, and if there is no idle thread, a new thread is created.) Note that when Goroutine executes, the thread is not recycled, but instead becomes the idle thread. )
If the current goroutine does not block, it will not give up the CPU to other goroutine, in the above code instance, the output will be one goroutine, and if the sleep function is used, the current goroutine is blocked. The current goroutine actively let the other goroutine execute, so the concurrency is formed.

Code instance

It is also possible to use Goroutine to achieve true parallel effects, with two solutions:
1, allow go to use multi-core (runtime. Gomaxprocs)

var quit chan int = make (chan int) func Loop () {for I: =  0; I < i++ {//in order to observe, run more fmt. Printf ( "%d", I)} quit <- 0}func Main () {runtime. Gomaxprocs (2) //use up to 2 cores go Loop () go Loop () for I: = 0; I < 2; i++ {<-quit}}              

2, manual explicit Transfer (runtime. gosched)

func loop() {    for i := 0; i < 10; i++ {        runtime.Gosched() // 显式地让出CPU时间给其他goroutine fmt.Printf("%d ", i) } quit <- 0}func main() { go loop() go loop() for i := 0; i < 2; i++ { <- quit }}

Execution Result:

0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9

The second way to voluntarily let go of CPU time is still to run in a single core. But the hand site switching Goroutine led to the seemingly "parallel".

Third, runtime

The runtime Scheduler is a magical thing, but I hope it doesn't exist, and I want the explicit dispatch to be more natural and multicore processing turned on by default.

About the runtime package several functions:
Gosched ()//yield CPU
NUMCPU ()//Returns the number of CPU cores for the current system
Gomaxprocs ()//Set the maximum number of simultaneous CPU cores to be used
Goexit ()//exit current goroutine (but defer statement will execute as usual)

Iv. Summary

By default all Goroutine will run in a native thread, or only one CPU core is used by default. If the current goroutine does not block, it will not give up the CPU time to other goroutines of the same thread, this is the Go runtime on the Goroutine dispatch, we can also use the runtime package to manually dispatch.
If we turn on multicore, when a goroutine is blocked, go will automatically transfer the other goroutines with the goroutine on the same system thread to another system thread so that these goroutines do not block. This allows for parallel effects.

Reference from: https://studygolang.com/articles/5463

Go language concurrent Programming (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.