惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
M
MIT News - Artificial intelligence
U
Unit 42
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
I
InfoQ
WordPress大学
WordPress大学
H
Help Net Security
D
Docker
B
Blog
腾讯CDC
A
About on SuperTechFans
Recent Announcements
Recent Announcements
雷峰网
雷峰网
有赞技术团队
有赞技术团队
C
Check Point Blog
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker
Go Language concurrency and an easy pitfall
Ashish Bhatia · 2021-10-03 · via ashishb.net

What should this code print?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
  "fmt"
  "sync"
)

func main() {

  arr := []int {1, 2, 3}

  var wg sync.WaitGroup
  for i := 0; i < len(arr); i++ {
    wg.Add(1)
    // Start a thread to do some heavy work in the background
    go func() {
      fmt.Printf("i is %d\n", i)
      wg.Done()
    }()
  }
  // Wait till all the threads finish
  wg.Wait()
}

Instead of printing

1
2
3
i is 0
i is 1
i is 2

It generates

1
2
3
i is 3
i is 3
i is 3

What happened?

Turns out that the reference to i is captured but not the value. So when the internal anonymous function runs, it gets the current value of i at the time of execution and not creation.

One general rule for this is to never access value from the outer function directly, instead pass those values as parameters.

Consider this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
  "fmt"
  "sync"
)

func main() {

  arr := []int {1, 2, 3}

  var wg sync.WaitGroup
  for i := 0; i < len(arr); i++ {
    wg.Add(1)
    // Start a thread to do some heavy work in the background
    go func(j int) {
      fmt.Printf("i is %d\n", j)
      wg.Done()
    }(i)  // Capture the value at the time of thread creation
  }
  // Wait till all the threads finish
  wg.Wait()
}

And it produces

1
2
3
i is 2
i is 0
i is 1

Update: This has been fixed in Go 1.22 and later.