Home > Article > Backend Development > 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) } }
Then compile
go build -o test_web.gobin ./test_web.gobin
Then access
curl 127.0.0.1:9000 Hello world!
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!