繁体   English   中英

Redigo 并发集提供数据竞争

[英]Redigo concurrent Set gives data race

我正在对我的 redigo 函数运行这个测试,看看它是否支持大量并发写入,这里是代码

import (
    "github.com/gomodule/redigo/redis"
    "log"
    "os"
)

// Redis connection pool
var RedisPool *redis.Pool

func InitPool() {
    RedisPool = &redis.Pool{
        MaxIdle:   80,
        MaxActive: 12000,
        Dial: func() (redis.Conn, error) {
            conn, err := redis.Dial("tcp", "127.0.0.1:6379")
            if err != nil {
                log.Printf("ERROR: fail init redis: %s", err.Error())
                os.Exit(1)
            }
            return conn, err
        },
    }
}

func ClosePool() error {
    return RedisPool.Close()
}

func Set(key string, val string) error {
    // get conn and put back when exit from method
    conn := RedisPool.Get()
    defer conn.Close()

    _, err := conn.Do("SET", key, val)
    if err != nil {
        log.Printf("ERROR: fail set key %s, val %s, error %s", key, val, err.Error())
        return err
    }

    return nil
}

func TestManySets(t *testing.T) {
    InitPool()
    defer ClosePool()

    var wg sync.WaitGroup
    numOfOperations := 1000
    for i := 0; i < numOfOperations; i++ {
        wg.Add(1)
        go func() {
            err := Set("key", strconv.Itoa(i))
            if err != nil {
                t.Errorf("error when setting key value: %s", err)
            }
            wg.Done()
        }()
    }
    wg.Wait()

    result, err := Get("key")
    if err != nil {
        t.Errorf("error when getting key value: %s", err)
    }
    t.Logf("result: %s", result)
}

使用go test -run TestManySets /path/to/package -count 1 -v运行测试时,我遇到了很多EOF错误;

并且在使用-race运行测试时,即go test -race -run TestManySets /path/to/package -count 1 -v我检测到很多数据竞争,任何人都可以向我指出我该怎么做事情对吗?

以下是数据竞赛日志:

ycx@DESKTOP-NBD349L:/mnt/c/Users/robbi/Projects/GoGameServer$ go test -race -run TestManySets visiontech.com/adapter -count 1 -v
=== RUN   TestManySets
==================
WARNING: DATA RACE
Read at 0x00c00009ab10 by goroutine 7:
  visiontech.com/adapter.TestManySets.func1()
      /home/ycx/Projects/GoGameServer/src/visiontech.com/adapter/redis_test.go:48 +0x3c

Previous write at 0x00c00009ab10 by goroutine 6:
  visiontech.com/adapter.TestManySets()
      /home/ycx/Projects/GoGameServer/src/visiontech.com/adapter/redis_test.go:45 +0x14c
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:865 +0x163

Goroutine 7 (running) created at:
  visiontech.com/adapter.TestManySets()
      /home/ycx/Projects/GoGameServer/src/visiontech.com/adapter/redis_test.go:47 +0x128
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:865 +0x163

Goroutine 6 (running) created at:
  testing.(*T).Run()
      /usr/local/go/src/testing/testing.go:916 +0x65a
  testing.runTests.func1()
      /usr/local/go/src/testing/testing.go:1157 +0xa8
  testing.tRunner()
      /usr/local/go/src/testing/testing.go:865 +0x163
  testing.runTests()
      /usr/local/go/src/testing/testing.go:1155 +0x523
  testing.(*M).Run()
      /usr/local/go/src/testing/testing.go:1072 +0x2eb
  main.main()
      _testmain.go:62 +0x222
==================
--- FAIL: TestManySets (10.08s)
    redis_test.go:62: result: 1000
    testing.go:809: race detected during execution of test
FAIL
FAIL    visiontech.com/adapter  10.098s
ycx@DESKTOP-NBD349L:/mnt/c/Users/robbi/Projects/GoGameServer$

redis_test.go 第 47 行是上面代码中Set发生的地方。

比赛是因为你的 for 循环正在更新i而你的 goroutines 正在同时读取i 解决此问题的一种方法是将i传递到您的 goroutine function 中:

for i := 0; i < numOfOperations; i++ {
    wg.Add(1)
    go func(i int) {                             // <----------- CHANGE THIS
        err := Set("key", strconv.Itoa(i))
        if err != nil {
            t.Errorf("error when setting key value: %s", err)
        }
        wg.Done()
    }(i)                                         // <----------- AND THIS
}

这样你就不再有对i的闭包,并且你的 goroutine function 中的i是一个独特的值,可以在不受外部干扰的情况下读取(或写入)。

这也解决了竞争检测器找不到的另一个错误:在for循环中,递增的变量被重新使用,这意味着您当前的版本实际上在许多情况下无意中使用了相同的i值,并跳过了其他版本。 有关更多信息,请参见此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM