duanjuda5789 2016-04-20 20:46
浏览 13
已采纳

在并发环境中从地图上删除是否安全? 在高朗

Do I put the lock before removing the item from map?

package main

import ( 
    "errors"
    "sync"
    "time"
)

type A struct {
    Error error
}

func (a *A) Job() {
//    ... more job
}

var l sync.RWMutex

func generate() {
    l.Lock()
    values["key1"] = A{}
    l.Unlock()
    l.Lock()
    values["key2"] = A{}
    values["key3"] = A{}
    l.Unlock()
 //   ...
    l.Lock()
    values["key1919"] = A{Error: errors.New("oh...")}
    l.Unlock()
 //   ...
    l.Lock()
    values["key99999999999"] = A{}
    l.Unlock()
}

var values map[string]A

func main() {
    values = make(map[string]A)
    go generate()

    for {
        l.RLock()
        for key, value := range values {
            if value.Error != nil {
                delete(values, key)    // it's safe? or you need to take a lock?
            } else {
                value.Job()
            }   
        }
        l.RUnlock()
        time.Sleep(10 * time.Second)
    }
}

Variants:

  1. delete in range without worrying

  2. add key in slice and separate range for to remove them

  3. l.RUnlock(); l.Lock(); delete(values, key); l.Unlock; l.RLock(); in range

  4. go l.delete(key) // gorutin splash

Which variant is the effective removal with lock/unlock?

  • 写回答

1条回答 默认 最新

  • doudoulb1234 2016-04-20 21:04
    关注

    Deleting from a map is considered a write operation, and must be serialized with all other reads and writes. If I understand your question correctly, then yes you need to either batch the deletes for later, or give up the read lock and take a write lock to complete the delete.

    The runtime attempts to detect concurrent reads and writes, and will crash with one of:

    fatal error: concurrent map writes
    fatal error: concurrent map read and map write
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?