Repository navigation
Expand file tree
/
Copy pathindex.xml
More file actions
38 lines (31 loc) · 2.19 KB
/
Copy pathindex.xml
File metadata and controls
38 lines (31 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>BetaCat.Dev</title>
<link>https://betacat.dev/</link>
<description>Recent content on BetaCat.Dev</description>
<generator>Hugo -- gohugo.io</generator>
<language>en-us</language>
<copyright>This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.</copyright>
<lastBuildDate>Fri, 22 Mar 2019 00:00:00 +0000</lastBuildDate>
<atom:link href="https://betacat.dev/index.xml" rel="self" type="application/rss+xml" />
<item>
<title>循环中的闭包陷阱</title>
<link>https://betacat.dev/posts/closure-trap-in-loop/</link>
<pubDate>Fri, 22 Mar 2019 00:00:00 +0000</pubDate>
<guid>https://betacat.dev/posts/closure-trap-in-loop/</guid>
<description>在 go 中进行循环操作时, 对于批量任务, 大多都会用 goroutine 来并发处理. 下面代码使用了 goroutine + closure
1 2 3 4 5 for _, val := range values { go func() { fmt.Println(val) }() } 相信熟悉的同学们已经看出来了, 这段代码是有问题的. 循环中变动的变量, 如果直接在闭包使用, 会导致 goroutine 处理时拿到的值可能是重复的值. 因为循环迭代使用了同一个变量, 所以每个闭包也都共享了这一个变量. 当闭包开始运行, 程序在 println 执行时打印了val的值, 但这个值在 goroutine 启动时可能已经被修改了, 或者说可能被修改了很多次. 可以用go vet来判断是否有此类似的问题.
为了绑定当前的val到每个启动后的闭包中, 需要在循环中新增变量. 一个方法是 将变量对闭包进行参数传递, 如下:
1 2 3 4 5 for _, val := range values { go func(val interface{}) { fmt.</description>
</item>
<item>
<title>About Me</title>
<link>https://betacat.dev/about-me/</link>
<pubDate>Wed, 09 Apr 2014 00:00:00 +0000</pubDate>
<guid>https://betacat.dev/about-me/</guid>
<description>操着码农的心去改变世界
对技术保持热情, 对精通保持敬畏:)</description>
</item>
</channel>
</rss>