Comments (5)
“上面的代码有严重的内存泄漏问题,出错的位置是 go fn(i),实际上代码执行后会启动 4 个协程,但是因为 ch 是非缓冲的,只可能有一个协程写入成功。而其他三个协程会一直在后台等待写入。”
type query func(string) string
func exec(name string, vs ...query) string {
ch := make(chan string)
fn := func(i int) {
ch <- vs[i](name)
}
for i, _ := range vs {
go fn(i)
}
return <-ch
}
func main() {
ret := exec("111", func(n string) string {
return n + "func1"
}, func(n string) string {
return n + "func2"
}, func(n string) string {
return n + "func3"
}, func(n string) string {
return n + "func4"
})
fmt.Println(ret)
}
实际上4个协程都不能写入成功,因为ch是一个空的channel
from interview-go.
空的channel是什么意思?
from interview-go.
空的channel是什么意思?
应该ch := make(chan string, 1)
from interview-go.
这是不是空channel,是无缓冲channel,需要有一个读才能有一个写,这个题目里面只有一个读操作,所以也只可能有一个写操作成功。
from interview-go.
明白了,谢谢
引用别人的话:
“无缓冲的 就是一个送信人去你家门口送信 ,你不在家 他不走,你一定要接下信,他才会走。
无缓冲保证信能到你手上
有缓冲的 就是一个送信人去你家仍到你家的信箱 转身就走 ,除非你的信箱满了 他必须等信箱空下来。
有缓冲的 保证 信能进你家的邮箱”
from interview-go.
Related Issues (20)
- 第三题的答案是否使用了额外的空间 HOT 1
- gpm窃取过程不对 HOT 1
- 常见语法题目 一 的第6题,CAS操作 HOT 3
- 一些建议 HOT 4
- 语法找错题 最后一道解答错误
- question17/多协程切片查询
- 最长公共前缀 go版本代码有误
- 第六题机器人坐标计算有问题
- 冒泡排序完全是错的 HOT 1
- “实现阻塞读且并发安全的map”答案补充 HOT 1
- q001中的chan类型应该用struct{}
- 实现 Sunday 匹配 needle在最末尾的时候返回结果异常
- 读阻塞且并发安全的 Map,答案是否有问题?
- 最接近的三数之和,代码有误
- Goroutine泄露问题——交替打印数字和字母
- q006 机器人坐标,L 跟 R指令是不是调转了
- 判断字符串中字符是否全都不同为什么有个127的判断?
- 『goroutine和channel使用一』 答案协程泄露
- interview-go/question /q015.md
- q007常见语法题 第8题
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from interview-go.