Giter VIP home page Giter VIP logo

Comments (5)

laotoutou avatar laotoutou commented on May 18, 2024

“上面的代码有严重的内存泄漏问题,出错的位置是 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.

lifei6671 avatar lifei6671 commented on May 18, 2024

空的channel是什么意思?

from interview-go.

laotoutou avatar laotoutou commented on May 18, 2024

空的channel是什么意思?

应该ch := make(chan string, 1)

from interview-go.

lifei6671 avatar lifei6671 commented on May 18, 2024

这是不是空channel,是无缓冲channel,需要有一个读才能有一个写,这个题目里面只有一个读操作,所以也只可能有一个写操作成功。

from interview-go.

laotoutou avatar laotoutou commented on May 18, 2024

明白了,谢谢
引用别人的话:
“无缓冲的 就是一个送信人去你家门口送信 ,你不在家 他不走,你一定要接下信,他才会走。

无缓冲保证信能到你手上

有缓冲的 就是一个送信人去你家仍到你家的信箱 转身就走 ,除非你的信箱满了 他必须等信箱空下来。

有缓冲的 保证 信能进你家的邮箱”

from interview-go.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.