dte29947 2017-05-05 08:00
浏览 42
已采纳

没有互斥锁,并发处理切片无法按预期工作

Functions WithMutex and WithoutMutex are giving different results.

WithoutMutex implementation is losing values even though I have Waitgroup set up.

What could be wrong?

Do not run on Playground

P.S. I am on Windows 10 and Go 1.8.1

package main

import (
    "fmt"
    "sync"
)

var p = fmt.Println

type MuType struct {
    list []int
    *sync.RWMutex
}

var muData *MuType
var data *NonMuType

type NonMuType struct {
    list []int
}

func (data *MuType) add(i int, wg *sync.WaitGroup) {
    data.Lock()
    defer data.Unlock()
    data.list = append(data.list, i)
    wg.Done()

}

func (data *MuType) read() []int {
    data.RLock()
    defer data.RUnlock()
    return data.list
}

func (nonmu *NonMuType) add(i int, wg *sync.WaitGroup) {
    nonmu.list = append(nonmu.list, i)
    wg.Done()

}

func (nonmu *NonMuType) read() []int {
    return nonmu.list
}

func WithoutMutex() {
    nonmu := &NonMuType{}
    nonmu.list = make([]int, 0)
    var wg = sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go nonmu.add(i, &wg)

    }
    wg.Wait()
    data = nonmu
    p(data.read())
}

func WithMutex() {
    mtx := &sync.RWMutex{}
    withMu := &MuType{list: make([]int, 0)}
    withMu.RWMutex = mtx
    var wg = sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go withMu.add(i, &wg)
    }
    wg.Wait()
    muData = withMu
    p(muData.read())
}

func stressTestWOMU(max int) {
    p("Without Mutex")
    for ii := 0; ii < max; ii++ {
        WithoutMutex()
    }
}

func stressTest(max int) {
    p("With Mutex")
    for ii := 0; ii < max; ii++ {
        WithMutex()
    }
}

func main() {
    stressTestWOMU(20)
    stressTest(20)
}
  • 写回答

1条回答 默认 最新

  • dongtang1997 2017-05-05 08:07
    关注

    Slices are not safe for concurrent writes, so I am in no way surprised that WithoutMutex does not appear to be consistent at all, and has dropped items.

    The WithMutex version consistently has 10 items, but in jumbled orders. This is also to be expected, since the mutex protects it so that only one can append at a time. There is no guarantee as to which goroutine will run in which order though, so it is a race to see which of the rapidly spawned goroutines will get to append first.

    The waitgroup does not do anything to control access or enforce ordering. It merely provides a signal at the end that everything is done.

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

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计