106 points · by benhoyt · 6y ago · 122 comments
Have another goroutine receive and output the "found" results, rather than doing it in the first loop. Now you have a proper pipeline.
The big win with goroutines is that they're green threads. They can block, and you can have lots of them. With regular threads, too many will use up resources. With "async", anything that blocks or just takes too long locks up the whole system. Go has the best of both worlds, which is very useful for the case of a server holding open connections to a huge number of human-paced clients.
There are some async APIs for regular files and we've got io_submit coming in, but it's still not a complete solution and never will be.
On the other hand, spawning threads works everywhere and is cheap enough.
AFAIK this is true on Linux but it’s not true on Windows, which allows “overlapped I/O” on files. Not sure about other operating systems.
I figured this out in Go about 30 minutes after I realized I needed to limit concurrency, and I'm a dumbass, basically.
So, I'm not sure that "still not easy" is accurate, especially given that I have a lot of trouble conceptualizing async and await, as used in C#. In fact, I don't think I've ever successfully used that paradigm in C#. I've been told that C# async and await are "easy" and this article says Go concurrency is "still not easy" and I've had the exact opposite experience in both cases.
In fact I really don't understand why async and await is even a thing anymore, given the paradigm that Go uses and the example it sets. It is almost supernatural in its ease, for me.
Modula-2, Concurrent Pascal, Active Oberon already had similar constructs.
Async/await are configurable, not only can you replace the task scheduler algorithms, if the type being applied on does provide some magic methods, the runtime will use them instead of the default ones.
This allows for very powerful concurrency optimizations and workflows, that still look like plain async/await calls.
Nestable stackless coroutines cannot. By definition they require compiler support.
Your proposed solution will not have any of the advantages of stackless coroutines (effect typing of async functions and perfectly optimal memory use) while suffering all the performance penalty of running on top of a channel.
Programming with threads is hard because they can context-switch at arbitrary points. Goroutines are nothing more than (lightweight) threads.
Stackful coroutines (as in Lua) aren’t much better, because they can context-switch at any function call.
Code that uses async-await is different - it can only context-switch at points explicitly marked with `await`.
That's really what it comes down to: cooperative multi-tasking vs preemptive multi-tasking.
Windows 3.1 had cooperative multi-tasking. Everything went great until one program didn't yield control, and then the whole system ground to a halt. That should sound familiar to any Node.js developers with their event loop.
Cooperative multi-tasking also extremely complicates code that actually uses the CPU. If you look inside libuv, it even has to jump through hoops with its encryption functions by effectively calling yield() in between rounds of calculation.
I would have assumed the Yield was there to help with protect against timing pokes...
Goroutines don’t switch at arbitrary points, they get swapped out during IO, networking or sleeping (they’re cooperative not pre-emtive). So they’re not like threads in that fashion they’re more closer to JavaScripts event loop (I think both node and go use libuv?). The only difference is the await syntax isn’t needed because Go “awaits” by default, that is the coroutine will block and yield the thread while it waits.
That was only ever an implementation detail, though - you always had to program as though goroutines were preemptive. And sure enough, from Go 1.14, “Goroutines are now asynchronously preemptible” [0].
> Go “awaits” by default
Yes, the main selling point of async-await isn’t cooperative vs preemptive, it’s the explicit context switches compared to the implicit context switches of threads, goroutines and stackful coroutines.
So, you're right, but it has been addressed.
Since you're asking, Rust's ownership/type system, for example, has checks in place that prevent at least some classes of concurrency errors.
For example, you can't directly modify a variable from multiple threads, due to the so-called "move" rules:
let mut myvar = vec![];
thread::spawn(move || {
myvar.push(1);
});
myvar.push(1); // can't do this; variable has been movedIn other langs I'd expect to see this code use a generic map-reduce/parallel map helper function or something like that, but in Go people seem to be happier writing for-loops and spawning goroutines by hand every time.
Yes, other languages provide you with more tools than the basic nuts and bolts. For example a language might provide you with a "parallel for" primitive that is well tested.
The issue is not exactly that Go's concurrency stuff is bad, it's just that it doesn't give you much help so you have to implement it all yourself. Also the lack of generics means it is difficult to write libraries for this stuff.
Search for "race condition", or just "race".
This section in particular is about preventing data races: https://docs.adacore.com/spark2014-docs/html/ug/en/source/co...
This one is about preventing race conditions: https://docs.adacore.com/spark2014-docs/html/ug/en/source/co...
Stackful coroutines are not new - it might surprise you to know that they are older than async/await, existing in full form probably introduced at least in 1967, with the first documented implementations starting around 1958. Stackful coroutines were implemented in a wide array of popular languages in the 1980s as pjmlp noted.
Stackless coroutines need better clarification, since the paper that defined this term [2] refers to a limited subset of stackless coroutines that we would nowadays just call "generators". To the best of my knowledge, when the paper came out generators were the only type of stackless coroutine in existence, and thus came the perception that stackless coroutines cannot be nested (they can) and that stackful coroutines are strictly superior to stackless coroutines (they aren't). You can see an example discussion here: https://news.ycombinator.com/item?id=16318535
The real difference is not nesting, but the fact that stackful coroutines manage a growable stack dynamically at runtime, while stackless coroutines pass the job on to the compiler to evaluate all possible nesting permutations, and create an optimally memory-efficient stack machine that represents the coroutine.
To summarize the pros and cons of each, I think you can say:
Stackful pros:
* [No colored functions](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...) - summed up it says: I can write asynchronous I/O code the same way I write multi-threaded code or non-blocking code. It's definitely more ergonomic, but also means your code can hold more surprises for you. Not everybody thinks 'Colored Functions' are an absolute advantage, otherwise we wouldn't have Effect Typing. * Less GC allocations: stack is [re-]allocated in bulk every time time a lightweight starts (go statement) or whenever it needs to grow. Stackless coroutines typically allocate a smaller object on every call to an async function.
Stackless pros: * Clear yield points: you always know the points where your coroutine could suspend and control would be moved to another coroutine: whenever you see an await statement[3]. This is why function colors are needed - to be explicit about the control flow. * Less memory waste and less overall allocation size: the "compile-time stacks" generated by stackless coroutines are perfectly efficient. There is no unnecessary memory allocated.
I don't think it is clear that one model is strictly superior to the other, but I do believe that if you're aiming for ease of correct use (rather than ease of use), the stackless model is clearly better. It is definitely somewhat harder to wrap your mind around, but it is also somewhat harder to get a deadlock or have a hard-to-detect data race in this model.
[1] Simula 67 (and probably Simula I too), and first implemented in Assembly as early as 1958 by Melvin Conway of Conway's Law fame.
[2] http://www.inf.puc-rio.br/~roberto/docs/MCC15-04.pdf by Roberto Ierusalimschy, the author of Lua.
[3] It's slightly different in an awaitless language like Kotlin - here you actually have to check whether the function you're calling is suspendable or not.
Yes. Preference among programmers for one model or the other appears close to 50/50.
More languages seem to support stackless coroutines than stackful ones, although that could just be because they’re easier to retro-fit to an existing compiler/VM. It’ll be interesting to see which model new languages choose.
The compiler does not syntactically converts your awaits to callbacks - it converts everything into state machines.
If you're using .NET in your projects, you can start taking advantage of such tools _today_. I would like for such tools and testing techniques to become more and more common place in the industry as concurrent and distributed systems are _hard_ and we should use all the help we can get.
It sounds a bit like Coyote, which also looks very useful for C# applications.
Any modern language allows you to create threads (semantically equivalent to goroutines) and pass messages between them. Most of them even have high-level concurrency support such as parallel map, structured concurrency, reactive extensions, type-safe generic collections...
We could say that Golang makes concurrency using thread semantics scale to a large number of threads. When this paradigm is appropriate, then indeed Go is nice. The select statement is nice. But this is not always the right approach.
Yes, it is true that go needs slightly fewer characters to launch a naked thread than in C# or Java. In that sense, it is easier. Anyone who considers that a major selling point is a walking race condition.
As a tongue in cheek analogy, what if we consider my new language G, in which G is an alias for goto. G is going to finally make control flow easy. I've done away with complicated control flow constructs such as for or while - users wouldn't understand them anyway. Users are encouraged to use the G keyword liberally. After all, it's only 1 character. Indeed, by that metric, it's even simpler than go's go keyword. What could go wrong?
Simplified:
var wg sync.WaitGroup
wg.Add(jobs)
ch := make(chan workItem, jobs)
for i := 0; i < jobs; i++ {
go func() {
defer wg.Done()
for item := range ch {
processItem(item)
}
}()
}
for _, item := range items {
ch <- item
}
close(ch)
wg.Wait()https://play.golang.com/p/AB6exUIkNRg
Contents pasted below.
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
e := NewParallelExecutor(uint64(10))
for i := 0; i < 100; i++ {
wg.Add(1)
func(_i int) {
//make closure to capture i correctly
e.Submit(func() {
fmt.Println(_i)
wg.Done()
})
}(i)
}
wg.Wait()
fmt.Println("All done.")
}
type Executor interface {
Submit(func())
}
type parallelExecutor struct {
queue []func()
inCh chan func()
doneCh chan struct{}
}
func NewParallelExecutor(limit uint64) Executor {
pe := ¶llelExecutor{
queue: make([]func(), 0, limit),
inCh: make(chan func()),
doneCh: make(chan struct{}),
}
go func() {
running := uint64(0)
for {
select {
case <- pe.doneCh:
running -= 1
case f := <- pe.inCh:
pe.queue = append(pe.queue, f)
}
if len(pe.queue) > 0 && running < limit {
running += 1
fmt.Println(fmt.Sprintf("Goroutines in flight, waiting: %d | %d", running, len(pe.queue)))
f := pe.queue[0]
pe.queue = pe.queue[1:]
go func(_f func()) {
_f()
pe.doneCh <- struct{}{}
}(f)
}
}
}()
return pe
}
func (p *parallelExecutor) Submit(f func()) {
p.inCh <- f
}Languages that _actually_ make concurrency easy, such as Haskell, Scala, OCAML or distributed concurreny easy (Erlang/Elixir) are way ahead of Go but are not as hyped and are not marketing themselves as well.
In absolute terms? Yes In terms relative to the userbase? No In terms relative to how powerful or well-designed the language is? Certainly
But I don't see how such a purely mathematical viewpoint could fit nicely into the real-time world where processes evolve concurrently and can take different times to do things on different executions. In the real world things are mutable, and concurrent programming must take that into account. Therefore it is "complicated".
https://learnyousomeerlang.com/distribunomicon
> distributed programming is like being left alone in the dark, with monsters everywhere. It's scary, you don't know what to do or what's coming at you. Bad news: distributed Erlang is still leaving you alone in the dark to fight the scary monsters. It won't do any of that kind of hard work for you. Good news: instead of being alone with nothing but pocket change and a poor sense of aim to kill the monsters, Erlang gives you a flashlight, a machete, and a pretty kick-ass mustache to feel more confident
> This is the standard 'tools, not solutions' approach seen before in OTP; you rarely get full-blown software and applications, but you get many components to build systems with. You'll have tools that tell you when parts of the system go up or down, tools to do a bunch of stuff over the network, but hardly any silver bullet that takes care of fixing things for you.
As for the weird syntax, I use Elixir (https://elixir-lang.org/) on the daily and its pretty great. See here for a different write up I did https://news.ycombinator.com/item?id=24173635
If you want a 1000 households to visit a set of shops in a repeatable Random order until the shops runs out of stock, that’s a List sort with a seed and a sequential loop
Make the 1000 households concurrent and sending messages and it becomes a major exercise in clocking, scaling and scheduling.
Same for OS threads. We use green threads in Scala for a long time now, there is a great amount of library support. Here is some example: https://zio.dev/docs/overview/overview_basic_concurrency
It is the same story as with garbage collection. Garbage collection prevents some kinds of errors and in general makes it way more easy to deal with dynamic memory allocations. However, garbage collections does not mean you don't have to think about allocation patters and object lifetime for example.
Go does make concurrency much easier by the tools it provides. Most importantly are goroutines, which are very lightweight, so within reasonable limits, you don't have to be concerned about the number of goroutines you spawen - but as the example shows, you shouldn't try to spawn more goroutines as there are file handles available to your process, if every goroutine allocates a file handle. Not only are goroutines very lightweight with small growable stacks, but as they are part of the language specification, the compiler can generate code which helps with scheduling, in most cases you have efficient cooperative sheduling, so thread-based preemption is less frequent.
On top of that, channels provide a very easy to use abstraction for communication between goroutines. There are a lot of use cases, where goroutines and channels give you very easy and safe concurrency. It does not save you from understanding concurrency issues and especially deadlocks. Which in a general sense is impossible to achieve, because to prove that a program is deadlock-free would require to prove that all goroutines return and that is equivalent to the halting problem, which is unsolveable.
It should also not be underestimated, that due to goroutines and channels being part of the language spec, these are very commonly used features. Concurrency is present in most Go programs. As a consequence, when one reads a lot of Go code, there will be plenty examples of their usage. And any library needs to be thread-safe as the likelyhood is very high that it does get called from goroutines.
Like if I have 3 definitions in a row that set variables to the result of methods that don’t share memory, that seems pretty obviously parallelizable. Why isn’t anyone doing these sorts of optimizations?
I would have thought it would have been solved by now, but I was wrong.
Fitting problems into grids of processing like SIMD or GPU's is tricky because not a lot of problems fit those well like images. Most of what you're asking for is about understanding business flow which a language will never do.
It would be cool if the compiler could construct a DAG of operations and automatically offload independent computations onto different cores.
I think this would necessitate a purely functional language, though.
I thought the whole point of limitCh is to support the case where len(pss) > concurrencyProcesses but in this case you're telling me that it's breaking things?
This would work if the consumer was started in a goroutine first.
See the playground: https://play.golang.org/p/pXJaGQ0efe8
Source Code is available on GitHub: https://github.com/go-training/training/blob/2ddb95d08c654a6...
I can’t recommend it high enough. It makes working with highly concurrent go so much easier and is a blessing for anybody with prior experience in Erlang or Akka.
For example, Go has no generic support for atomic primitives, arrays, slices, or maps. It has sync/atomic, but it's not generic. I always reach for Uber's atomic library, which has typesafe atomic wrappers such as atomic.Bool. They're so common, you'd think a CSP-aware language would provide keywords declare things atomic:
var b atomic[bool]
if cas(b, false, true) {
...
}
"Classical" Go didn't have errgroups, contexts or cancellation. To build something truly robust, "modern" Go ends up involving all three (plus atomics, of course). That's because almost all complex situations need to build what are effectively nested trees of goroutines that all need to quickly abort and unwind on errors or panics.But as you use more and more of these primitives, your code (or at least my code) becomes more and more obscured by the layers of error-handling, cancel-detection, retrying, and so on. I really wish some of this was built into the language, especially cancellation. For example, channels don't support contexts. So if you have a loop like this:
for evt := range taskCh {
handle(evt)
}
...then you have to rewrite it to support cancellation. So you have a few options. One is to select on both the channel and context: for {
select {
case evt := <-taskCh:
handle(evt)
case <-ctx.Done():
return ctx.Err()
}
}
Because of this, you can no longer use a for loop. Immediately the code got more bloated and less readable.Another option is to spawn a goroutine whose only job is to abort the channel:
go func() {
<-ctx.Done()
close(ch)
}()
for evt := range taskCh {
handle(evt)
}
return ctx.Err()
That's a bit better (and you could move the for loop into its own function for clarify, without changing anything else). But it's still worse than a simple for loop!As a real-world example, here [1] is some code I've been working on lately. A controller starts N workers that need to process a task queue. If the controller is stopped, all the workers need to stop. So I use the pattern above. But I can't use a for loop! That's because I use a task queue abstraction that needs to support features that Go channels don't.
I can't use a for loop or select block to block on the task queue, because only channels support that. So that's another problem with Go: Often, you can use raw channels as your data processing primitive if things are simple enough, but in practice, channels are best for coordination, and you have to build your own primitives — and yet, by building those primitives, you lose language expressiveness.
To address the concrete example, I'd love to do this instead:
// Range over task queue (custom object with blocking
// semantics), automatically cancel if ctx is cancelled
for task := range taskQueue with ctx {
handle(task)
}
[1] https://gist.github.com/atombender/6bcff2c2d8fec32bc80ce1f57...What we see with golang is a phenomenon where people just parrot what some well known figures said at some point in time, without proper evidence or any basis (and in some cases, even when the evidence is counter to those claims).
I'm looking forward to Java's green thread implementation (project Loom), as it has proper ways to manage cancellation and deadlines and hierarchies, all of which have are quite verbose and error prone, or not supported at all in golang.