golang--- 32位系统下atomic.AddUint64导致程序崩溃及解决办法

http://www.baidu.com/link?url=qb02vICS8NhIztRZ1n7wWHiJ6bDGFeIKQQQfr0w0BShbImeG_EuBkDGEiGzYUF44vQUB6lk_6z11UVP4fcDtonzmlvY0LM6fy-t-Yu6bDIa
          
   发表于1小时前(2014-02-12 10:44)  
阅读(7) | 评论( 0

0人收藏此文章,

赞0

package main

import (
	"sync/atomic"
	"unsafe"
)

type a struct {
	x unsafe.Pointer
	y uint64
}

func main() {
	p := new(a)
	atomic.AddUint64(&p.y, 1)
}

在32位计算机上运行改程序,会出现错误:

panic: runtime error: invalid memory address or nil pointer dereference

[signal 0xc0000005 code=0x0 addr=0x0 pc=0x4198bc]

goroutine 1 [running]:

runtime.panic(0x41c740, 0x445e4f)

C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/runtime/panic.c:266 +0xa6

sync/atomic.AddUint64(0x114434ac, 0×1, 0×0, 0x4107e3, 0x397fcc)

C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist550409343/go/src/pkg/sync/atomic/asm_386.s:118 +0xc

main.main()

E:/Work/GoLang/src/demo/goBug/atomic/main.go:17 +0x4d

查了资料具体原因如下:

https://code.google.com/p/go/issues/detail?id=5278

On x86-32, the 64-bit functions use instructions unavailable before the

   Pentium MMX. On both ARM and x86-32, it is the caller’s responsibility to

   arrange for 64-bit alignment of 64-bit words accessed atomically. The

   first word in a global variable or in an allocated struct or slice can be

   relied upon to be 64-bit aligned.

其大意是:

64位原子操作的调用者必须确保指针的地址是对齐到8字节的边界

的办法有两种:

1,修改uint64字段在struct 的位置确保字段地址出现在8字节的边界;

2,修改使用sync.RWMutex来实现互斥,如下

mutex.Lock()
uint64 += 1
mutex.Unlock()

建议使用办法2来彻底解决问题


声明:OSCHINA 博客文章版权属于作者,受法律保护。未经作者同意不得转载。

No tags for this post.
除非注明,本站文章均为原创或编译,转载请注明: 文章来自 KENGINE | Kankanews.com
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值