dragon87836215 2015-04-21 08:22
浏览 39

多个执行例程等待共享计时器导致比赛

I have a requirement to update timer of a shared object in multiple go routines. But it end up with race condition. I cannot use lock for waiting on the channel because all the other routines will have to wait.

package main
import( 
    "time"
    "math/rand"
)
type R struct {
    timer *time.Timer
    //other fields
}

func f(done chan bool,r *R){
    r.timer =time.NewTimer(time.Millisecond * time.Duration(1000 + rand.Intn(2)))
    //some code simultaneously accessing other fields of shared object r, cannot put a lock here
    <-r.timer.C

    done <- true
}

func main(){
    done := make(chan bool , 5)
    var r *R
    var t *time.Timer
    r = &R{timer:t}
    for i:=0;i<5;i++{
        go f(done,r)
    }
    for i:=0;i<5;i++{
        <-done
    }
}

when I run using

 go run -race thread.go

it gives

==================

WARNING: DATA RACE
Write by goroutine 5:
  main.f()
      usr/local/gocode/thread.go:12 +0x69

Previous write by goroutine 4:
  main.f()
      usr/local/gocode/thread.go:12 +0x69

Goroutine 5 (running) created at:
  main.main()
      usr/local/gocode/thread.go:25 +0xd3

Goroutine 4 (running) created at:
  main.main()
      usr/local/gocode/thread.go:25 +0xd3
==================

and hangs

any help would be useful

  • 写回答

1条回答 默认 最新

  • dougutuo9879 2015-04-21 10:23
    关注

    There is a design issue here - you have one R object, and it has a shared instance, but every goroutine creates a new timer that is local. Seems to me like you need a local timer per goroutine, and not share that timer between all of them, it just doesn't make sense.

    If you rewrite your code like so:

    type R struct {
        //other fields
        Foo string
        Bar interface{}
    }
    
    func f(done chan bool, r *R) {
        timer := time.NewTimer(time.Millisecond * time.Duration(1000+rand.Intn(2)))
        //some code simultaneously accessing other fields of shared object r, cannot put a lock here
        <-timer.C
    
        done <- true
    }
    

    the timer becomes local to the goroutine as it should be, and you have no race condition, at least for the timer access.

    Note that still, ever access to the shared object's other fields must be protected by a mutex or you'll get the same issue.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值