[Golang note] Co-process Foundation

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

The concept of co-process

The process is often called coroutine, which is called Goroutine in Golang.

The process is essentially a user-state thread, which does not require an operating system for preemptive scheduling and is stored in the threads in the actual implementation.

The cost of the co-path system is minimal, which can effectively increase the task concurrency of a single thread, thus avoiding multithreading. And the use of the process of programming simple, clear structure. The disadvantage is the need for programming language support, if not supported, you need the user in the program to implement the scheduler itself.

Goroutine

goroutine is a lightweight threading implementation in Golang, managed by Go runtime.

goroutine using syntax

// defining the function of a thread  funcmyroutinefunction(parameter list) (return value list) {    //  function Body }//  Start the process gomyroutinefunction(parameter list)

start a goroutine using the Go keyword, go is the most important keyword in Golang, so the language is also named with this keyword.

with the Go keyword call in front of a function, this call is executed concurrently in a new goroutine, and the thread that opened Goroutine will continue to execute .

When a function called by go returns, the Goroutine is automatically ended. If the function has a return value, the return value is discarded .

The Golang program executes from the main () function, and when the main () function returns, the program ends without waiting for the other goroutine to end .

Goroutine Use Example

Package   mainimport ("FMT"    "Time")func Add(x, yint) {z:= x +y fmt. Println (z)} func Main () {     forI: =0; I <Ten; i++{ go Add(i, i)} fmt. Println ("main Goroutine finished!") time. Sleep (3*Time . Second)}

The results of the program running two times are as follows:

It can be seen that Goroutine does appear to be executing concurrently and the result is uncertain.

Concurrency and parallelism

• concept

Two queues, one coffee machine, that is concurrent.

Two queues, two coffee machines, that is parallel.

Golang concurrency and parallelism

Concurrent execution

If in the case of a single-core CPU, all Golang Goroutine can only run in one thread.

If the current goroutine does not block, it is not going to give the CPU time to other goroutine unless the runtime is called. Gosched () voluntarily conceded the time slice.

If the current goroutine is blocked, it will voluntarily give up CPU time to other goroutine execution.

the Golang runtime package is a Goroutine scheduler, which uses runtime. Gomaxprocs (n) can control the number of CPU cores used.

Example One

Package   mainimport "FMT"Import"Time"
Import "Runtime" func Loop() {fmt. Println("Loop starts!") forI: =0; I <Ten; i++{fmt. Printf("%d", i)} fmt. Println ()}func main() {
Runtime. Gomaxprocs(1) //mandatory use of 1 CPUs
Go Loop () go Loop() time. Sleep (3*Time . Second)}

The results of the operation are as follows:

Example Two

Package   mainimport ("FMT"
"Runtime" "Time")func Add(x, yint) {z:= x +Y fmt. Println (z)} func Main () {
Runtime. Gomaxprocs(1) //mandatory use of 1 CPUs
go Add( 0,0) go Add(1,1) go Add(2,2) go Add(3,3) go Add(4,4) go Add(5,5) go Add(6,6) go Add(7,7) go Add(8,8) go Add(9,9) fmt. Println ("main Goroutine finished!") time. Sleep (3*Time . Second)}

The results of the operation are as follows:

Parallel execution

By default, Golang is turned on multicore, so the output from the first example is unordered.

We can also tell Golang we allow the maximum number of cores to be used at the same time.

Example One

Package   mainimport "FMT"Import"Time"Import"Runtime" func Loop() {fmt.  Println("Loop starts!")     forI: =0; I <Ten; i++{fmt.  Printf("%d", I)} Fmt. Println ()}func main() {runtime.  Gomaxprocs(2) go loop () go loop () go loop (       ) go Loop() time. Sleep (3*Time . Second)}

       runs several times, Results can be obtained:

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.