golang-Concurrent Programming Goroutine

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. How the server program improves concurrency:
    • Multi-process, multi-threaded model, this mode is now basically not
    • Using multiplexing (such as actor-mode Epoll, Proactor-mode IOCP, etc.) + callback structure, this model not only does not conform to people's sequential thinking habits, but also error-prone.
    • With the use of a co-process (lightweight threading, the cost of creating and destroying it is very small), the process executes in a logical order.

Why do you want to introduce the server model? Because Golang's goroutine is the co-process.

There are many programming languages that have associated libraries, but they are not fully functional, for example, C + + can be implemented using Setjump and Longjump. As I know, there are Erlang and Golang that support the process at the language level. Compared with Erlang and Golang, Golang is easier to understand and easier to get started with.


The use of Goroutine (Golang) in the Channel,channel is similar to the UNIX pipe (pipe) function, which is mainly used to communicate between multiple goroutine.

For example, the following program uses two goroutine to calculate the sum of a set of data:

Package Mainimport "FMT" func calcsum (arr []int, res chan int) {        var sum = 0        for _, V: = range arr {                sum + = v
  }        Res <-sum}func Main () {        var res = make (chan int)        var arr = []int{1, 2, 3, 4, 5, 6, 7, 8, 9}        go CA Lcsum (Arr[:5], res)        go calcsum (arr[5:], res)        sum: = <-res        sum + = <-res        FMT. Println ("sum =", sum)}

The function calcsum calculates the sum of the incoming data and, after the calculation is completed, puts the result into the channel, and the main process calculates the summation and output of the two sub-processes through the channel.

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.