Go Language Practical Notes (12) | Go Goroutine

Source: Internet
Author: User
Tags terminates
This is a creation in Article, where the information may have evolved or changed.

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes. If you feel helpful, share it with your friends and thank you for your support.

Before we talk about Goroutine, we'll talk about concurrency and parallelism.

General procedures, if not specifically required, are sequential execution, such programs are easy to write maintenance. But with the development of technology and the evolution of business, we have to write programs that can be parallel, because there are many benefits.

For example, when you read the article, you can also listen to music, this is the system of parallel, at the same time can do a lot of things, the full use of computer multicore, improve the performance of software operation.

In the operating system, there are two important concepts: one is a process, one is a thread. When we run a program, such as your IDE or QQ, the operating system will create a process for the program, which contains the various resources required to run the program, which can be said to be a container, a workspace that belongs to the program, such as memory space, file handles, devices and threads, and so on.

So what is a thread? A thread is a space for execution, such as downloading a file, accessing a network, and so on. A thread is called by the operating system to run a code task written on a different processor, which is not necessarily the process in which the program is located. Operating system scheduling is responsible for the operating system, different operating systems may not be the same, but for our program writers, do not care, because it is transparent to us.

When a process starts, it creates a main thread, and when the main thread ends, the process terminates, so a process has at least one thread, which is the main reason why we have to wait for the main course when we use goroutine in the function, because the main thread is over, The program terminates, then it is possible to see the output of the goroutine.

The go language concurrency refers to the ability to run a function independently of other functions, a goroutine is a separate unit of work, and the runtime of Go will dispatch these goroutine to run on the logical processor , a The logical processor binds an operating system thread, so goroutine is not a thread, it is a co-process, and this is the reason that it is implemented by the algorithm of the go language runtime itself.

Here we summarize the next few concepts:

Concept Description
Process A program that corresponds to a separate program space
Thread One execution space, one process can have multiple threads
Logical processor Executes the created goroutine, binds a thread
Scheduler Go runtime, assigning goroutine to different logical processors
Global Run queue All the goroutine you just created will be here.
Local Run queue Goroutine Queues for logical processors

When we create a goroutine, it is stored in 全局运行队列 , waiting for the go runtime to 调度器 be dispatched, assigning them to one of them, 逻辑处理器 and placing them in the corresponding logical processor 本地运行队列 , and finally waiting to be 逻辑处理器 executed.

This set of management, scheduling, execution goroutine is called go concurrency. Concurrency can do a lot of things at the same time, such as having a goroutine executed in half, is suspended to perform other goroutine, this is the Go control management. So the concept of concurrency is not the same as parallel, parallel refers to the different physical processors at the same time to execute different code snippets, parallel can do a lot of things at the same time, and concurrency is to manage a lot of things , because the operating system and the total resources of the hardware is relatively small, so the concurrency effect is much better than parallel, Using less resources to do more things is also advocated by the go language.

The concurrency principle of go we just talked about, so what's the parallel to go? In fact, the answer is very simple, create one more 逻辑处理器 , so that the scheduler can simultaneously allocate 全局运行队列 the goroutine to different 逻辑处理器 on the parallel execution.

 1234567891011121314151617 
 < span class= "keyword" >func  main   ()   {var  wg sync. Waitgroupwg.add (2 ) go  func   ()   {defer  WG. Done () for  i:=1 ; I<100 ; i+ + {FMT. Println (, I)}} () go  func   ()   {defer  WG. Done () for  i:=1 ; I<100 ; i+ + {FMT. Println ( "B:" , I)}} () WG. Wait ()} 

This is a simple concurrency program. Creating a goroutine is a go keyword, followed by a function or method.

Here sync.WaitGroup is actually a count of the semaphore, the purpose of using it is to main wait for the function of two goroutine to complete and then end, or the two are goroutine still running, the program is over, see the desired results.

sync.WaitGroupis also very simple to use, first using the Add method set the calculator to 2, each goroutine function after the execution, the call Done method minus 1. WaitThe method means that if the counter is greater than 0, it will block, so the main function waits for 2 goroutine to complete before ending.

We run this program, we will find that the A and B prefixes will cross, and the results of each run may be different, this is the result of the Go Scheduler Scheduler.

By default, go defaults to assigning a logical processor to each available physical processor because my computer is 4-core, so the above example creates 4 logical processors by default, so there are parallel schedules in this example, and if we force only one logical processor, let's look at the results.

123456789101112131415161718
 func  main  Span class= "params" > ()   {runtime. Gomaxprocs (1 ) var  wg sync. Waitgroupwg.add (2 ) go  func   ()   {defer  WG. Done () for  i:=1 ; I<100 ; i+ + {FMT. Println (, I)}} () go  func   ()   {defer  WG. Done () for  i:=1 ; I<100 ; i+ + {FMT. Println ( "B:" , I)}} () WG. Wait ()} 

Setting the number of logical processors is also very simple, at the beginning of the program to use runtime.GOMAXPROCS(1) , here is set to 1. We'll run this time and we'll find a first, then print B.

Here we do not mistakenly think is sequential execution, here the reason for the sequential output is because our Goroutine execution time is too short, before we can switch to the 2nd Goroutine, 1th Goroutine completed. Here we can take each goroutine the execution time to lengthen some, can see the concurrency effect, here no longer the example, everybody tries.

For the number of logical processors, not the more the better, according to the actual physical number of computers, if not multicore, set up a number of logical processors is useless, if you need to set, generally we use the following code settings.

1
Runtime. Gomaxprocs (runtime. NUMCPU ())

So for concurrency, it is the go language itself implementation of the scheduling, for parallel, is the running of the computer's physical processor of the number of cores, multicore can be parallel concurrency, single core can only be concurrent.

"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes. If you feel helpful, share it with your friends and thank you for your support.

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.