5 ms·
Is this really true? My impression was that the 'go' keyword means a green thread is spun up for the function to run in and this wrapper returns immediately (he
by valzam 4y ago
Is this really true? My impression was that the 'go' keyword means a green thread is spun up for the function to run in and this wrapper returns immediately (hence the need for channels or waitgroups etc to get the results back). I can't imagine that every synchronous function call creates a green thread, that seems massively wasteful.
- cube2222 4y agoIt doesn't create a green thread. I meant async in the technical underlying runtime sense of not blocking an OS thread when doing seemingly blocking operations and tried to describe it in an approachable way. Async in the sense of a python or rust function that is declared as async. If you think in terms of function colors (async and non-async) Go only has async ones. The `await` and `go` bit are an intuition about how Go works, where waiting for the result right away is the default, while running concurrently needs to be called for. It of course doesn't create needless goroutines on every function call.
- eweise 4y agoI don't see anything in the docs about cancelling a standard function. Maybe internally Go represents a function as some type of future but for all practical purposes, it looks to me like a function in Go is just as synchronous as as a function in say java.
- cube2222 4y agoThere's a big difference. If you write to a file using the stdlib in java, you will block an OS thread. In Go you won't. That does not mean all Go calls are cancelable, they're not. If, in a Scala/Python/Rust async function you use a synchronous stdlib function, that call will block the whole OS thread with it. The following experiment will show you the difference: In Java, run 10 futures on a threadpool of 4 workers, with each future doing a thread.Sleep(1s). That will finish after 3 seconds. In Go, run 10 goroutines with GOMAXPROCS=4, with each doing time.Sleep(1s). That will finish after 1 second.
- eweise 4y agoYes I understand the difference between threads and fibers. That is a much different conversation than "All functions async by default and preemptible."
- cube2222 4y agoIf you run non-async (blocking) code in a fiber, then it will block the underlying OS thread. Functions need to be compiled in a special way and use IO in a very specific way (async io) in order for them to be properly runnable by fibers. This specific way is commonly referred to as "async", or "nonblocking", and all functions in Go are that way, including all IO functions available in the stdlib.