首页 > 编程语言 > 详细

GO语言不要用共享内存来通信,要用通信来共享内存

时间:2020-09-29 23:12:13      阅读:62      评论:0      收藏:0      [点我收藏+]

这句话是推荐使用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()能操作内存,达到了 "让同一块内存在同一时间内只被一个线程操作" 的目的

GO语言不要用共享内存来通信,要用通信来共享内存

原文:https://www.cnblogs.com/longzhankunlun/p/13751724.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!