这句话是推荐使用channel来实现 "让同一块内存在同一时间内只被一个线程操作" 的目的
先看一个简单的示例代码
package main import ( "fmt" "net/http" ) var j int func HelloServer(w http.ResponseWriter, req *http.Request) { j++ fmt.Println(j) } func main() { http.HandleFunc("/", HelloServer) http.ListenAndServe(":8080", nil) }
每个http请求都会创建一个新的goroutine,在高并发下,多个goroutine对全局变量 j 进行同时读写。有可能造成这么一个局面:
前面一个goroutine在 j++ 之后,此时 j 值为5,本来应该输出5的,结果输出之前另一个goroutine又执行了一次 j++ ,这样一来 j 值就为6,然后两个goroutine一起输出了6
下面两个方法可以解决该问题:
1. 前者 - 【用共享内存来通信】,就是上锁。将例子中代码修改如下
package main import ( "sync" "fmt" "net/http" ) var j int var m sync.Mutex // 互斥锁 func HelloServer(w http.ResponseWriter, req *http.Request) { m.Lock() j++ fmt.Println(j) m.Unlock() } func main() { http.HandleFunc("/", HelloServer) http.ListenAndServe(":8080", nil) }
将用户要进行业务流程之前上锁,执行完后解锁。这样每次同一时间就只有一个goroutine在操作内存变量了
2. 后者 - 【要用通信来共享内存】,就是使用goroutine + channel,将例子中代码修改如下
package main import ( "fmt" "net/http" ) var j int var chGoto = make(chan int) func HelloServer(w http.ResponseWriter, req *http.Request) { // 将干活信号传给goroutine chGoto <- 1 } func rec() { for { // 等待干活信号 <- chGoto // 开始干活 j++ fmt.Println(j) } } func main() { // 先创建一个goroutine go rec() http.HandleFunc("/", HelloServer) http.ListenAndServe(":8080", nil) }
主协程专门创建一个goroutine用来操作内存,创建完毕后rec()堵塞,等待其他goroutine往chGoto传值,假设http请求A往chGoto传值,当rec()执行完A传入的 <- chGoto 之后,另一个http请求B紧接着又会向chGoto传值,但此时rec()还在执行从A传值chGoto的for循环里还没执行的语句,执行完后rec()再从chGoto中取出B的传值。这样一来高并发下多个goroutine只有依靠单个rec()能操作内存,达到了 "让同一块内存在同一时间内只被一个线程操作" 的目的
原文:https://www.cnblogs.com/longzhankunlun/p/13751724.html