Understanding Golang Concurrent Programming

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

Concurrency vs Parallelism

Concurrency and parallelism are two concepts that are related to each other, but are not entirely equivalent. In the program, concurrency emphasizes the combination of independently executed programs, while parallel emphasis is performed on simultaneous computation tasks [1].

The number of computer cores determines the ability of parallel computing, people as "single-core" animals (except the old naughty little Dragon girl), can say oneself in concurrent certain tasks, such as I am listening to the song write code, but should not think that these two things in parallel execution, reference:

The concurrency model of Golang originates from the communicating sequential Processes (CSP), which implements the concurrency programming pattern by providing goroutine and channel.


Goroutine

Goroutine is created and managed by the Go runtime, which is the "smallest unit" that go uses to schedule CPU resources, and lighter than the OS thread [2]:

    • Lower memory consumption requires only 2kB of initial stack space, and the thread initially wants 1Mb of space;

    • Created and destroyed by the Golang runtime environment, more inexpensive and does not support manual management;

    • Higher switching efficiency.


The relationship between Goroutine and threads is as follows:

with Goroutine You can make a function and other functions run in parallel, we can easily create hundreds or thousands of goroutine without reducing the execution efficiency of the program. Just precede the function call with the go keyword, and you can create a goroutine,ni bu ni hai?

The main function itself is also a goroutine[3].

Give me a chestnut:

Output:

begin Main Goroutine

End Main Goroutine

The result of the output, and the wood has the begin Hello Goroutine, because, by using goroutine, we do not need to wait for the return result of the function call, but then execute the following code. Add time after go hello () . Sleep (1 * time. Second), let go run time to slow the god son, will output.


Channel

Go provides a mechanism to enable communication and synchronization between multiple goroutine, which is the channel. The channel is a type that defines the type of channel as a combination of the type of the keyword chan and the channel transport content. Defined by var c chan string = Make (Chan string) , the type of transmission in this channel is a string. It can also be abbreviated as var c = Make (Chan string) or c:= Makes (Chan string) .

The channel variable is manipulated by the left-arrow <- operator:

    • c <-"Ping " means sending a string with a value of "ping" to the channel,

    • msg: = <-C Represents a value in the Receive channel and is assigned a msg.

Output:

reveving : 1

reveving : 2

reveving : 3

...

by function, the channel can be divided into only send or receive channel, by modifying the function signature of the channel parameter type to specify the channel's "direction":

    • Allow send only: func Ping (c chan<-string)

    • Allow only receive: func Print (c <-chan string)

    • Any receive operation that only sends a channel and a send operation that receives only the channel will generate a compilation error

    • A channel that does not specify a direction is called a "bidirectional" channel, and a "bidirectional" channel can be passed as a parameter to a function that receives a one-way channel, or vice versa.


Unbuffered Channel

Non-buffered channel, that is, a buffer pool size of 0 channel or synchronous channel, the above pest use is non-buffered channel, defined by:

    • CH: = make (chan int)

    • CH: = Make (chan int, 0)

When receiving data from a non-buffered channel, the receiver is blocked if there is no data in the channel, and if there is data in the channel the sender is blocked until the data in the channel is received.

Using non-buffered channel, data exchange can be used to guarantee the state synchronization of two goroutine.


Buffered Channel

The buffer channel can only hold a fixed amount of data, and when the buffer pool is full, the sender is blocked until the data is received to release the buffer pool, as defined below:

    • CH: = Make (chan int, 5)

Buffer channel can be used to limit throughput, as follows:

Above the pest, we define a buffer channel with a capacity of 5, whenever a request is received from the request queue, a signal is sent to the channel, then a new goroutine is processed to process the request, and when the processing is complete, the buffer pool is released (receiving a signal). By doing so, you can limit the number of requests for concurrent processing to no more than 5. Every 4 seconds, the output:

Process

Process

Process

Process

Process


Select

For Channel,golang provides a keyword select that functions like switch , with the following basic principles:

    1. Select selects the first ready channel for processing

    2. If there is more than one channel ready, a channel is randomly selected for processing

    3. If there is no channel ready, wait until a channel is ready

    4. If there is default , it does not wait in 3, but immediately executes the statement in default

After two seconds, the output:1 . in the SELECT statement, add:

Default

Fmt. Println ("nothing received.")

Then, when the program executes, it will immediately output: ' Nothingreceived. `


Summarize

Golang abstraction of threads into lightweight goroutine, developers no longer need to focus too much on OS-level operations and finally be freed from concurrent programming.

Channel, as the medium of communication, realizes the communication and memory sharing between goroutine safely and efficiently.

Finally, use effetive go in a sentence to summarize [4]:

Do not communicate by sharing memory; Instead, share memory by communicating.


Reference

[1] Https://blog.golang.org/concurrency-is-not-parallelism

[2] http://blog.nindalf.com/how-goroutines-work/

[3] Https://www.golang-book.com/books/intro/10

[4] Https://golang.org/doc/effective_go.html





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.