dongpaozhi5734 2015-05-31 21:49
浏览 34
已采纳

使用goroutines时将函数调用包装到闭包中

This question already has an answer here:

Wrapping a function call into a closure leads to an unexpected behaviour when using goroutines.

Consider the following example:

package main

import (
    "log"
    "sync"
    "time"
)

var workerNum = 5
var wg sync.WaitGroup

func block() {
    dur := 300 * time.Millisecond
    //time.Sleep()
    select {
    case <- time.After(dur): {}
    }
}

func startWorker(worker int) {
    for i:=0; i < 3; i++{
        log.Printf("Worker %d woke up! 
", worker)
        block()
    }
    wg.Done()
}

func main() {
    for i:=0; i < workerNum; i++ {
        //go func() { startWorker(i) }()
        go startWorker(i)
    }

    wg.Add(workerNum)
    wg.Wait()
}

Test it here: http://play.golang.org/p/nMlnTkbwVf

One can see that wrapping startWorker(i) into func() { startWorker(i) }() results in calling only the 5-th worker.

It looks like there is something wrong in the way how closures capture variables from the outer scope. Why is this happening? Do closures use pass-by-reference way for passing outer variables instead of pass-by-value?

</div>
  • 写回答

1条回答 默认 最新

  • douyun3887 2015-05-31 21:54
    关注

    That's how closures in all languages work, if you want to do it that way, you have to isolate the variable.

    go func(i int) { startWorker(i) }(i)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!