Go Language Quest-12 (ending)

Source: Internet
Author: User

The previous article focused on the interface, reflection, and error and exception handling in the go language. This article focuses on the process of the go language, and of course the last chapter of the Go Language Foundation.

Goroutine:

Goroutine is the core of go parallel design and the essence of this language. The Goroutine keyword is the co-process, but it is smaller than the thread. Speaking of threads, we may not be strangers. Thread, which is the smallest unit that the program executes. A standard thread consists of a thread ID, a current instruction pointer, a collection of registers, and a stack. In addition, the thread is an entity in the process, is the basic unit that is dispatched and dispatched by the system independently, the thread does not own the system resources, only has a bit of resources that are essential in the operation, but it can share all the resources owned by the process with other threads belonging to one process.

Now the Go language uses the process of a smaller execution unit than the thread, more than 10 goroutine may be reflected in the bottom is five or six threads, the go language inside to help you realize the memory sharing between these goroutine. Execution goroutine requires very little stack memory (presumably 4~5kb) and will, of course, scale according to the corresponding data. Because of this, thousands of concurrent tasks can be run concurrently. Goroutine is easier to use, more efficient and lighter than thread.

Goroutine is a thread manager managed through the runtime of Go. The role of goroutine is a common function. Here is how the process is written and the results tested:

Test-1


Test-2


Test-3

In theory: multiple goroutine run in the same process, sharing memory data, but designed to follow: do not communicate through sharing, but share through communication. The goroutine runs in the same address space, so access to shared memory must be well synchronized. So how does data communicate between Goroutine, go provides a good communication mechanism: Channel.

The channel is a core type in go, and you can think of it as a conduit through which the core unit can send or receive data for communication.

First, the channel must be created and reused, plus its operator is the arrow <-

The definition Format for channel type (three ways) is as follows:

Channeltype = ("Chan" | "Chan" "<-" | "<-" "Chan") data type

Among them, the <-here represents the channel direction. If the direction is not specified, then the channel is bidirectional, which means that the data can be received or sent.

(it is said that the channel can be seen as a conduit, since it is a pipe flow). This is the following three ways of writing:

Chan t//can receive and send data of type T

chan<-float64//can only be used to send data of type float64

<-chan int//can only be used to receive data of type int

Other than that:

<-is always preferred and the leftmost type is combined. Here are a few combinations:

chan<-Chan int//equivalence chan<-(chan int)

chan<-<-chan int//equivalent chan<-(<-chan int)

<-chan <-chan int//equivalent <-chan (<-chan int)

Capacity (capacity):

The channel can also be initialized with make, and the channel capacity can be set:

The capacity here can be understood as how many elements the channel can store, the buffer size of the channel is specified, and the other nil channel does not communicate.

Writing:

CH: = Make (chan type, value)

When value = 0 o'clock, it is also indicated that the channel is non-buffered blocking read and write;

When value > 0 o'clock, the channel is buffered and non-blocking until a value element is filled to block the write. For example:

Capacity

The above code does not change, when we set the capacity to 1, there will be the following problems:

Insufficient capacity

Range and close

Range, this keyword can be like operation slice or map, to manipulate the buffer type of channel;

Close, this keyword is mainly used to close the channel. No more data can be sent after the channel is closed.


Rang

The code above is only one channel, so what do we do if there are multiple channel?

The go provides a keyword selectthat allows you to monitor the flow of data on the channel via select.

It is similar to switch, but is only used to handle communication (communication) operations. It can be a Send statement (send), a receive statement (receive), or default.

Default is when the channel of the listener is not ready to execute

Select is blocked by default and only runs when there is a send or receive in the channel being monitored, and when multiple channel is ready, select randomly chooses one to execute.

The code is as follows:

Func Main () {

c: = make (chan int)

Quit: = make (chan int)

Go func () {

For I: = 0; I < 3; i++ {

Fmt. Println ("<-c = =", <-c)

}

Quit <-0

}()

Testselect (c, quit)

}

Func Testselect (c, quit Chan int) {

X, Y: = 1, 1

for {

Select {

Case C <-x:

X, y = y, x + y

Fmt. Println ("x = =", x)

Fmt. Println ("y+x = =", y+x)

Case <-Quit:

Fmt. Println ("Quit")

Return

}

}

}

Timeout Processing: timeout

A very important application of select is time-out processing. If no case needs to be handled in select, the SELECT statement will remain blocked.

At this point we may need a timeout operation to handle timeouts to prevent the entire program from getting stuck. Time-out processing of the go language is the timeout keyword used

Here is an example of a recurrence timeout, which I have divided into two scenarios:

Here is the second scenario where the recurrence timeout occurs:

Recurrence timeout

Here are some of the functions that were collected in the runtime package for handling Goroutine:

A:goexit This function means: exits the currently executing goroutine, but the defer function also continues to invoke

B:gosched This function means: Give up the execution permission of the current goroutine, the scheduler schedules other waiting tasks to run, and resumes execution from that location the next time.

C:numcpu This function means: Returns the number of CPU cores

D:numgoroutine This function means: Returns the total number of tasks being executed and queued

E:gomaxprocs This function means: To set the maximum number of CPU cores that can be computed in parallel and return the previous value.

Conclusion:

The basic content of the go language is basically finished. It is also considered as a study note and summary of this stage.

Golang in the process of learning, the most profound personal experience is the memory of the ultra-strict control management, simple syntax, smaller and more accurate implementation unit, function return value and so on.

Although the internet on such a mixed language, but still hope that the language can develop more and more good.

If this article is helpful to you, I hope you crossing leave a valuable star, thank you.

Ps: Copyright belongs to the author, reproduced please indicate the author, commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source (beginning or end please add reprint source, add original URL address), article do not abuse, also hope that we respect the author's labor results

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.