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

推荐订阅源

Last Week in AI
Last Week in AI
D
DataBreaches.Net
腾讯CDC
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
云风的 BLOG
云风的 BLOG
罗磊的独立博客
月光博客
月光博客
MyScale Blog
MyScale Blog
U
Unit 42
Martin Fowler
Martin Fowler
Stack Overflow Blog
Stack Overflow Blog
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
G
Google Developers Blog
博客园 - 【当耐特】
D
Docker
I
InfoQ
雷峰网
雷峰网

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.