dongliang2058 2019-02-13 20:22
浏览 26

同步访问同一变量

I want to make sure that my update function is executed only by one thread at a time for a given value.

func update1(int id){
   ...
   makeUpdate(id)
   ...
}

func update2(int id){
   ...
   makeUpdate(id)
   ...
}

So, how should I write my makeUpdate() function that the myUpdate block is executed only once for a given id value? That means if update1 is updating the record with the id "15" and update2 with the id "20", the block access should not be synchronized.

  • 写回答

1条回答 默认 最新

  • dousuiben8395 2019-02-15 20:11
    关注

    As comments suggest - you need to protect data access not functional access.

    Easiest way to achieve this, is to make a struct type with a lock - and attach the critical functional update as a method e.g.

    type MyData struct {
            l sync.Mutex
            // add any other task related attributes here too
    }
    
    // makeUpdate *MUST* use a pointer to our struct (i.e. 'm *MyData')
    // as Mutex logic breaks if copied (so no 'm MyData')
    func (m *MyData) makeUpdate(id int) {
            m.l.Lock()
            defer m.l.Unlock()
    
            fmt.Printf("better makeUpdate(%d)
    ", id) 
    
            // do critical stuff here
    
            // don't dilly-dally - lock is still being used - so return quickly
    }
    

    Try this out in the playground.

    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题