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)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案