douzhong6480 2014-07-10 15:51
浏览 16
已采纳

前往:匿名功能仅在范围内取最后一个值

I imagine this is a pretty easy fix. Just trying loop through the string list urls and print out each url as the loop iterates. But when I add in concurrency (with go and WaitGroup) all it prints out is the last url in the list.

Why is it only printing out the last url (when printed from the anon function) rather than each url individually as the loop iterates?

Go Playground: http://play.golang.org/p/z4IZLY7Mt_


Code:

package main

import (
    "fmt"
    "sync"
)

var urls = []string{
    "http://google.com",
    "http://facebook.com",
    "http://youtube.com",
    "http://yahoo.com",
    "http://baidu.com",
    "http://wikipedia.org",
    "http://twitter.com",
    "http://live.com",
    "http://amazon.com",
    "http://linkedin.com",
    "http://google.co.in",
}

func main() {
    var wg sync.WaitGroup
    for _, url := range urls {
        fmt.Println("correct: " + url)
        wg.Add(1)
        go func() {
            fmt.Println("wrong: " + url)
            wg.Done()
        }()
    }

    wg.Wait()
}
  • 写回答

1条回答 默认 最新

  • dongque6377 2014-07-10 16:00
    关注

    Here is the working code:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    var urls = []string{
        "http://google.com",
        "http://facebook.com",
        "http://youtube.com",
        "http://yahoo.com",
        "http://baidu.com",
        "http://wikipedia.org",
        "http://twitter.com",
        "http://live.com",
        "http://amazon.com",
        "http://linkedin.com",
        "http://google.co.in",
    }
    
    func main() {
        var wg sync.WaitGroup
        for _, url := range urls {
            fmt.Println("correct: " + url)
            wg.Add(1)
            go func(url string) {
                fmt.Println("wrong: " + url)
                wg.Done()
            }(url)
        }
    
        wg.Wait()
    }
    

    Also on go playground: http://play.golang.org/p/zFSDvfdIDS

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统