4 ms·
> The article seems to argue that it's hard to run more code after the completion of a goroutine. But, the entire point is you don't have to. Go does async i/o
by curryst 6y ago
> The article seems to argue that it's hard to run more code after the completion of a goroutine. But, the entire point is you don't have to. Go does async i/o under the hood, so you just write the lines of code sequentially in the order you want them to happen, and they will happen at the right time.
That seems a little hard to believe. If I do this:
db, _ := sql.Dial("")
defer db.Close()
go myFunc(db)
It will close my DB connection while myFunc is still running (assuming myFunc isn't trivial enough that it sometimes runs before the close can happen).
The author seems like they were more concerned about how 'go' tends to break abstractions. The additional flow control means that I do actually have to care how the library is implemented. I have to understand how they handle the lifecycle of objects I pass in, and then I have to figure out how to stop their stuff (and to stop it at the right time). DB connections are one of the things in Go that are frequently not closed or not closed correctly. The lack of a "with" kind of statement requires me to write a bunch of IPC so I can tell goroutines to quit, then wait for them to quit, and then finally close the connection. A lot of people (myself included when I'm being a bad programmer) just call 'os.Exit' and figure the DB will clean up the stale connections.
- mykowebhn 6y agoUsing a waitgroup will fix your problem in your example.
- cratermoon 6y agoGo convention would be to pass a 'done' channel to myFunc and only close the db on receipt of a message on the channel.