Go Series Tutorial--21. Go co-process

Source: Internet
Author: User
Tags terminates
This is a creation in Article, where the information may have evolved or changed. Welcome to the 21st chapter of [Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2). In the previous tutorial, we explored concurrency and the differences between concurrency and parallelism. This tutorial will show you how to use Go Association (goroutine) to implement concurrency in the Go language. # # What is Go Association? The Go process is a function or method that runs concurrently with other functions or methods. The Go process can be thought of as a lightweight thread. The cost of creating a Go process is small compared to a thread. So in the Go app, it's common to see thousands of go threads running concurrently. # # Go Process benefits compared to threading-the go process cost is extremely low compared to threading. The stack size is only a few kilobytes and can be increased or decreased depending on the application's needs. The thread must specify the size of the stack and its stack is fixed. -The Go process will reuse (multiplex) a smaller number of OS threads. Even if the program has thousands of Go processes, there may be only one thread. If a Go coprocessor in the thread is blocked (for example, waiting for user input), then the system creates an OS thread and moves the rest of the go to the new OS thread. All of this is done at runtime, and as programmers, we don't face these complex details directly, but have a neat API to handle concurrency. -The GO process uses the channel to communicate. A race condition (Race Condition) occurs when a channel is used to prevent multiple threads from accessing shared memory. A channel can be thought of as a conduit for communication between Go processes. We'll discuss the channel in more detail in the next tutorial. # # How do I start a Go association? When calling a function or method, precede the keyword ' go ' to allow a new go to run concurrently. Let's create a go association. "' Gopackage mainimport (" FMT ") func hello () {fmt. Println ("Hello World Goroutine")}func main () {go Hello () fmt. Println ("Main function")} "[Online Run Program] (Https://play.golang.org/p/zC78_fc1Hn) on line 11th, ' Go Hello () ' launches a new Go association. Now the ' Hello () ' function and the ' main () ' function are executed concurrently. The main function is run on a specific Go association, which is called Go main process (main goroutine). * * You will be surprised to run the program! * * The program will only output text ' main function '. What happened to the Go process that we started? To understand this, we need to understand the main nature of the two Go processes. -* * When a new process is started, the call of the co-process returns immediately. Unlike functions, program control does not wait for the go process to complete. After calling go, program control immediately returns to the next line of code, ignoring any return values for that process. * * * * If you want to run other go, the go main process must continue to run. If the go Master process terminates, the program terminates, and the other go threads do not continue to run. * * Now you should be able to understand why our go process is not running. After calling ' Go Hello ' in line 11th, the program control does not wait for the ' hello ' to end, immediately returns to the next line of code, printing ' main function '. Then, because there is no other executable code, the Go master process terminates, so the ' hello ' coprocessor has no chance to run. We will fix this problem now. "' Gopackage mainimport (" FMT "" Time ") func hello () {fmt. Println ("Hello World Goroutine")}func main () {go Hello () time. Sleep (1 * time. Second) fmt. Println ("Main function")} ' [Online Run Program] (https://play.golang.org/p/u9zzusql8-) in line 13th of the above program, we call the function in time package [' Sleep '] ( https://golang.org/pkg/time/#Sleep), the function sleeps the Go process that executes it. Here we make the Go main process hibernate for 1 seconds. So before the main process terminates, the call to go Hello () will have enough time to execute. The program first prints ' Hello World goroutine ', waits 1 seconds, then prints ' main function '. Using hibernation in the Go Master process to wait for the rest of the process to finish, this method is just a technique for understanding how the Go process works. The channel can be used to block the Go main process before other threads end execution. We'll discuss the channel in the next tutorial. # # Start multiple go routines to better understand go Process, we write a program that starts multiple Go processes. "' Gopackage mainimport (" FMT "" Time ") func numbers () {for i: = 1; I <= 5; i++ {time. Sleep (* time.millisecond) FMT. Printf ("%d", i)}}func alphabets () {for I: = ' a '; I <= ' e '; i++ {time. Sleep (Time.millisecond) fmt. Printf ("%c", i)}}func main () {go numbers () go alphabets () time. Sleep (* time.millisecond) FMT. Println ("main terminated")} "[Online Run Program] (https://play.golang.org/p/u9zzusql8-) in the above program in line 21st and 22nd, launched two Go Association. Now, the two threads run concurrently. The ' numbers ' process first sleeps 250 microseconds, then prints ' 1 ', then sleeps again, prints ' 2 ', and so on, until the end of print ' 5 '. The ' alphabete ' process also prints letters from ' a ' to ' e ', and has a sleep time of 400 microseconds each time. The Go Main Association starts the ' numbers ' and ' alphabete ' two go, sleeps after 3000 microseconds and terminates the program. The program outputs: "' 1 a 2 3 B 4 C 5 D E main terminated ' ' program works as shown. To see the picture better, open it in the new tab. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-series/Goroutines-explained.png) The first blue figure represents ' numbers ', the second brown-red figure represents ' alphabets ', the third green graph represents the Go main process, and the last black figure merges the above three kinds of processes to show how the program works. At the top of each box, strings such as ' 0 ms ' and ' Ms ' represent the time in microseconds. At the bottom of each box, ' 1 ', ' 2 ', ' 3 ' and so on represent the output. The blue Box says, ' 1 ms ' prints out ' 2 ', and so on. The bottom value of the last black box will be ' 1 a 2 3 B 4 C 5 D E main terminated ', which is also the output of the entire program. The piece is very intuitive and you can use it to understand how the program works. This concludes the introduction to the Go process. Have a nice day. * * Previous tutorial-[concurrency] (https://studygolang.com/articles/12341) * * * Next tutorial-[channel] (https://studygolang.com/articles/12402) * *

via:https://golangbot.com/goroutines/

Author: Nick Coghlan Translator: Noluye proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,359 Reads
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.