druybew06513 2018-11-17 11:24
浏览 61
已采纳

了解原子加法和互斥量

I'm testing the concurrency of incrementing itemID in the handler func below, and sometimes the increment skips a value (example: 4, 6, 7, ... skipped id 5).

func proxyHandler() http.Handler {
    var itemID int32
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        proxy := httputil.NewSingleHostReverseProxy(url)
        proxy.ModifyResponse = func(res *http.Response) error {
            item := Item{
                ID: int(atomic.AddInt32(&itemID, 1)),
            }
            items.Add(item)
            return nil
        }
        proxy.ServeHTTP(rw, req)
    })
}

I solved it by using Mutex:

func proxyHandler() http.Handler {
    itemID := 0
    mux := sync.Mutex{}
    return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
        proxy := httputil.NewSingleHostReverseProxy(url)
        proxy.ModifyResponse = func(res *http.Response) error {
            mux.Lock()
            itemID++
            item := Item{
                ID: itemID,
            }
            items.Add(item)
            mux.Unlock()
            return nil
        }
        proxy.ServeHTTP(rw, req)
    })
}

I'd like to understand why atomic add didn't work as I was expecting, that is, generating a sequential value without gaps.

  • 写回答

1条回答 默认 最新

  • dshyu6866 2018-11-17 11:57
    关注

    atomic.AddInt32() is perfectly fine for concurrent use by multiple goroutines. That is why it is in the atomic package. Your issue is with Items.Add() which you have pointed out in the comments as not having any lock protection.

    This is a rough definition for a safe Items.Add()

    type Items struct {
        items []Item
        lock  sync.Mutex
    }
    
    func (i *Items) Add(item Item) {
        i.lock.Lock()
        defer i.lock.Unlock()
        i.items = append(i.items, item)
    }
    

    With the above definition of Items, you can now use your initial code with atomic.AddInt32(). However, I would like to point out that you must not read Items while other threads are appending to it. Even reads must be synchronized.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图