Golang Concurrency (ii)-Goroutine

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

What's wasting today is tomorrow to those who died yesterday; What's the future of hate now?

What you are wasting today is the tomorrow that the man who died yesterday expects, and what you dislike is now the future you will never go back to.

What is Goroutine

Goroutines is a function or method that runs concurrently with other functions or methods.

Goroutines can be thought of as lightweight threads. The cost of creating a goroutine is small compared to the thread. So its application typically has thousands of concurrently running goroutines.

Goroutines Superior to Threading Advantage

The goroutine overhead is small compared to threads. Their stack size is only a few kilobytes, and the stack grows and shrinks according to the needs of the application, while the thread, the stack size must be specified and fixed.

The Goroutine is multiplexed to a smaller number of OS threads. There may be only one thread in a program that has thousands of routines. If any of the goroutine in the thread block and wait for user input, another OS thread is created and the rest of the Goroutine is moved to the new OS thread. All of this is affected by the runtime, and we are abstracted from these complex details as programmers and get a clean API to handle concurrency.

Goroutines use channel for communication. Channel is designed to prevent resource contention when accessing shared memory using Goroutine. The channel can be thought of as a conduit for communication with a goroutine.

How to open a Groutine

Using the keyword go prefix function or method call will result in a new goroutine that runs concurrently.

Instance parsing:

package mainimport (      "fmt")func hello() {      fmt.Println("Hello world goroutine")}func main() {      go hello()    fmt.Println("main function")}

Output: Main function

Note : The Go Hello () at this point will open a new process and run in parallel with the main thread. However, the program returns immediately after calling Go Hello () and continues to the execution of main, ignoring the output of the Goroutine, then the main process does not wait for the end of the new process to exit directly.

If the main program terminates, then the program will be terminated and all other goroutine will terminate execution.

Start multiple Goroutine

Let's write a program that launches multiple Goroutine to better understand goroutine.

ackage mainimport (      "fmt"    "time")func numbers() {      for i := 1; i <= 5; i++ {        time.Sleep(250 * time.Millisecond)        fmt.Printf("%d ", i)    }}func alphabets() {      for i := 'a'; i <= 'e'; i++ {        time.Sleep(400 * time.Millisecond)        fmt.Printf("%c ", i)    }}func main() {      go numbers()    go alphabets()    time.Sleep(3000 * time.Millisecond)    fmt.Println("main terminated")}

Doubts:

You may wonder if after the first goroutine is created, where sleep then causes the second goroutine to clog or wait to be created, when the first goroutine output is complete, then the second goroutine is created and executed.

Answer:

As we said above, the main process main executes a simple call immediately after executing to go FUNC (), and does not care about any output executed by code in the new Goroutine. So main executes the code statement sequentially.

The top two goroutine are executed in parallel.

This is a simple introduction to the channel.

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.