Rus*_*sel 7 concurrency channel go
package main
import (
"sync"
"fmt"
)
var m = make(map[string]string)
var seen = make(map[string]bool)
func main() {
wg := new(sync.WaitGroup)
wg.Add(1)
ch := make(chan string)
go deduplicate(ch, wg)
toAdd := []string{"foo", "bar", "baz", "foo"}
for _, s := range toAdd {
ch <- s
}
wg.Wait()
fmt.Println(m)
}
func deduplicate(ch chan string, wg *sync.WaitGroup) {
for s := range ch {
if seen[s] {
wg.Done()
continue
}
seen[s] = true
go write(s)
}
}
func write(s string) {
m[s] = "written"
}
Run Code Online (Sandbox Code Playgroud)
上面的代码可以安全使用吗?请注意,多个字符串将同时写入映射m,但它们肯定是唯一值,因此不会多次写入字符串。
不,那不安全。密钥是否唯一并不重要。您需要避免并发写入或写入与读取并发。并发读取没问题。
您可以使用竞争检测器通过运行来查找此类问题go run -race myprog.go。请参阅https://golang.org/doc/articles/race_detector.html。
| 归档时间: |
|
| 查看次数: |
4976 次 |
| 最近记录: |