duanli12176 2018-02-01 21:16
浏览 56

程序运行时如何安全地交换内存映射?

I have a go service running that has a map in memory, say map1. The map data (keys and values) relies on a file stored in S3. A goroutine is running to monitor this file and if there are changes, downloads the file, parses it, and creates a new map, say map2. How can I swap the contents of map1 with map2 without causing other threads from reading inconsistent data?

Below I have the rough idea of how I was thinking of solving this problem. The output of the below program is a sequence of "map1-a", followed by sequence of "map2-a". The map was swapped. Is this the best way to do this?

package main

import (
    "fmt"
    "time"
)

func initializeAndMonitor() *map[string]string {
    map1 := make(map[string]string)
    map1["a"] = "map1-a"
    go func() {
        time.Sleep(5 * time.Second)
        map2 := make(map[string]string)
        map2["a"] = "map2-a"
        map1 = map2
    }()
    return &map1
}


func main() {
    map1 := initializeAndMonitor()
    for count := 0; count < 100; count = count + 1 {
        fmt.Println((*map1)["a"])
        time.Sleep(1 * time.Second)
    }
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2018-02-01 21:19
    关注

    This is the purpose of mutexes; wrap the reads and writes in a sync.RWMutex:

    package main
    
    import (
        "fmt"
        "time"
        "sync"
    )
    
    var mu = sync.RWMutex{}
    
    func initializeAndMonitor() *map[string]string {
        map1 := make(map[string]string)
        map1["a"] = "map1-a"
        go func() {
            mu.Lock()
            defer mu.Unlock()
            time.Sleep(5 * time.Second)
            map2 := make(map[string]string)
            map2["a"] = "map2-a"
            map1 = map2
        }()
        return &map1
    }
    
    
    func main() {
        map1 := initializeAndMonitor()
        for count := 0; count < 100; count = count + 1 {
            mu.RLock()
            fmt.Println((*map1)["a"])
            mu.RUnlock()
            time.Sleep(1 * time.Second)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效