英文:
Must I synchronise read and write operations when doing it from different goroutines?
问题
据我所知,每个对服务器的请求都会创建一个新的goroutine。例如(可能是不正确的代码,但这个主题不是关于它的):
package main
import "net/http"
var exampleMap map[string]string
func handlerPost(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        {
            exampleMap["test"] = test // 我需要同步这个写操作吗?
        }
    case "GET":
        {
            if v, ok := exampleMap["test"]; ok { // 那么读操作呢?
                fmt.Println(v)
            }
        }
    }
}
func main() {
    http.HandleFunc("/", handlerPost)
    http.ListenAndServe(":8080", nil)
}
这是否意味着像这样做是不安全的,我必须使用sync.Map(例如),如果这里的map是数据库查询呢?在这种情况下我该怎么办?谢谢!
英文:
As I know, every requests to the server creates new goroutine. For ex (probably incorrect code, but this topic is not about it):
package main
import "net/http"
var exampleMap map[string]string 
func handlerPost(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		{
			exampleMap["test"] = test // Must I syncrhonise this writing?
		}
	case "GET":
		{
			if v, ok := exampleMap["test"] { // And what about reading?
				fmt.Println(v)
			}
		}
	}
}
func main() {
	http.HandleFunc("/", handlerPost)
	http.ListenAndServe(":8080", nil)
}
Does it mean that its unsafe to do it like this and I have to use sync.Map (for example), and what about if instead map here was a database queries? What can I do in this case. Thank you!
答案1
得分: 2
exampleMap在多个goroutine之间共享,因此需要对其进行同步访问。可以使用互斥锁(mutex),或者使用读写锁(RWMutex)以提高性能:
var exampleMap map[string]string
var exampleMutex sync.RWMutex
...
exampleMutex.Lock()
exampleMap["test"] = test
exampleMutex.Unlock()
...
exampleMutex.RLock()
v, ok := exampleMap["test"]
exampleMutex.RUnlock()
if ok {
  ...
}
请注意,以上代码是用于同步访问exampleMap的示例。
英文:
exampleMap is shared among goroutines, so you have to synchronize access to it. A mutex would do, a RWMutex would perform better:
var exampleMap map[string]string 
var exampleMutex sync.RWMutex
...
exampleMutex.Lock()
exampleMap["test"] = test 
exampleMutex.Unlock()
...
exampleMutex.RLock()
v, ok := exampleMap["test"] 
exampleMutex.RUnlock()
if ok {
  ...
}
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论