Golang rand.Rand 并发panic: index out of range

栏目: Go · 发布时间: 5年前

内容简介:线上服务Panic,部分日志如下放狗搜了一下:math.Rand is not safe for concurrent usefrom:

线上服务Panic,部分日志如下

引用

err: runtime error: index out of range

Traceback:

goroutine 19209941 [running]:

...

panic(0x191d0e0, 0x2e078d0)

/usr/local/go/src/runtime/panic.go:502 +0x229

math/rand.(*rngSource).Uint64(...)

/usr/local/go/src/math/rand/rng.go:246

math/rand.(*rngSource).Int63(0xc438bb2a00, 0x0)

/usr/local/go/src/math/rand/rng.go:231 +0x8a

math/rand.(*Rand).Int63(0xc4279b3a70, 0x0)

/usr/local/go/src/math/rand/rand.go:82 +0x33

math/rand.(*Rand).Int(0xc4279b3a70, 0x0)

/usr/local/go/src/math/rand/rand.go:100 +0x2b

...

放狗搜了一下:math.Rand is not safe for concurrent use

from: https://github.com/golang/go/issues/3611

这个 issue 的 4 楼还提到 "top-level functions like strings.Split or fmt.Printf or rand.Int63 may be called from any goroutine at any time"

翻了一下源码,rand.Int() 用是自带 lock 的 globalRand 对象

func Int() int { return globalRand.Int() }

...

var globalRand = New(&lockedSource{src: NewSource(1).(Source64)})

...

type lockedSource struct {
  lk  sync.Mutex
  src Source64
}

...

func (r *lockedSource) Uint64() (n uint64) {
  r.lk.Lock()
  n = r.src.Uint64()
  r.lk.Unlock()
  return
}

看了下调用代码,之前的实现为了避免多个 goroutine 竞争同一个锁,所以 new 了一个 rand.Rand 对象,但没考虑到这个对象不支持并发。

最终的解决方案,是实现了一个 safeRander 。

具体代码不适合贴,核心逻辑是初始化 N 个 rand.Rand 对象和对应的 N 个锁,以及一个 index,每次调用 Int() 时,先 atomic.AddUint32(&index, 1) % N,加上对应的锁,再用对应的 rand.Rand 对象。

这样只要并发使用的goroutine不超过N个,就不会出现竞争;就算超过,竞争出现的频率也大幅减少了,而且也可以通过增加 N 来优化。

转载请注明出自,如是转载文则注明原出处,谢谢:)

RSS订阅地址: http://www.felix021.com/blog/feed.php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

区块链:定义未来金融与经济新格局

区块链:定义未来金融与经济新格局

张健 / 机械工业出版社 / 2016-6-18 / 49.00

从构建价值互联网的角度看,区块链的出现意味着从0到1。正因如此,本书章节结构与常见的体例不同,从第0章开始。第0章从文字与货币的起源出发,通过论述人类信息传递和价值传输手段的进步,说明区块链技术诞生的必然性。第1章用深入浅出的语言讲解区块链的本质、运行原理、颠覆性潜力以及区块链技术的现状与未来;第2章宏观讲述了区块链技术带来的新产品和新机遇,包括数字货币、互联网金融、物联网,以及新一代的基础设施;......一起来看看 《区块链:定义未来金融与经济新格局》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具