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.

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

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题