Home > Backend Development > Golang > The reason why golang can achieve high concurrency

The reason why golang can achieve high concurrency

(*-*)浩
Release: 2019-12-13 14:42:51
Original
2629 people have browsed it

The reason why golang can achieve high concurrency

Why go can achieve high concurrency

goroutine is the core of Go's parallel design. In the final analysis, goroutine is actually a coroutine, but it is smaller than a thread. Dozens of goroutines may be reflected in five or six threads at the bottom. The Go language helps you realize memory sharing between these goroutines. (Recommended learning: Go )

to execute Goroutine only requires a very small stack memory (about 4 ~ 5kb), of course, it will be scalable according to the corresponding data. Because of this, thousands of concurrent tasks can be run simultaneously.

Goroutine is easier to use, more efficient, and lighter than thread.

Some high-concurrency processing solutions basically use coroutines. Openresty also uses the coroutines of the Lua language to achieve high concurrency processing capabilities. PHP's high-performance framework Swoole is also currently using PHP's coroutines.

Coroutines are lighter and occupy less memory, which is the prerequisite for high concurrency.

How to achieve high concurrency in go web development

Learn go HTTP code. First create a simple web service.

package main
import (
    "fmt"
    "log"
    "net/http"
)
func response(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello world!") //这个写入到w的是输出到客户端的
}
func main() {
    http.HandleFunc("/", response)
    err := http.ListenAndServe(":9000", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
Copy after login

Then compile

go build -o test_web.gobin
./test_web.gobin
Copy after login

Then access

curl 127.0.0.1:9000
Hello world!
Copy after login

The above is the detailed content of The reason why golang can achieve high concurrency. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template