157 points · by stopachka · 4y ago · 122 comments
There's many interesting discussions one can have about the latter but the former turns into toxicity.
With that said. The Rust teams are very interestes in structured concurrency at the moment. Rust 1.63 is going to get scoped threads, which is structured concurrency for threading. Myself and others have also been looking into structured async, albeit it's not as easy to implement.
I personally love the concept and I hope it takes off. You rarely need long running background tasks. If you do, you probably want to have a daemon running along side your main application using structured primitives and then dispatch work to them instead. This really simplifies the mental model when you get used to it.
I have used structured concurrency with Kotlin and you are right, it is absolutely easier to reason about concurrent code that way.
https://elizarov.medium.com/structured-concurrency-722d765aa...
[0]: Mikkel Thorup. 1998. All structured programs have small tree width and good register allocation
I can see this being the next Big Data or NoSQL 'must have' bandwagon.
Yes, by necessity. We're 15 years after the end of the race for frequency, and the end of moore's law is getting ever closer. Concurrency and parallelism are becoming table stakes for both reactivity and performances. This means making them reliably usable and composable is getting more and more important.
I imagine folks writing Web software, UIs and heavy desktop applications will also benefit from these developments but those areas are out of my core expertise so I can't speak to exactly how useful structured concurrency will be for them however I can see very clear applications for my domain.
There is a middle ground before highly concurrent, and it's "I don't really care what you do, but please use the cores i can have and don't block the main thread thank you"
It is called a wait group. See for an example here: https://gobyexample.com/waitgroups
So, except for the syntactic sugar around it, the nurseries compare to creating a wait group in a block, spawn goroutines which each call Done() on the wait group on exit and at the end of the block call Wait() to errect the same boundary, nurseries do. Of course you can also pass the waitgroup object to any goroutine created inside goroutines. This is a very common pattern in Go, but indeed, it probably should be presented more clearly and up front in tutorials about goroutines.
So for that, I will keep the article around, it shows the concept nicely - perhaps I might do a pure "go" version of it, which then shows the go implementation of nurseries. Might be nice to add to the original article, that not only the presented python library is a solution, but also that there is a native go way of achieving that, as the article uses "go" as the negative example :p
Much like if/for etc has replaced goto, structured concurrency can replace goroutines. Note: goto can be used like an if or a for loop. You've just made the argument that goroutines can be used like 'nurseries'. You've essentially argued in favour of goto from the articles perspective
I want to note again that this article is not actually about go. It is the same in most languages with concurrency primitives.
The key takeaway is that having to manually manage waitgroups is room to make mistakes or to introduce spaghetti concurrency, while you might be used to it at this point, it doesn't make it the best system for the future of concurrency
I would agree, it would be nice to have a similar syntactic construct in go to enforce this pattern, though it is actually possible to basically implement that with higher order functions.
And yes, I think goto has a place in any language, if you are aware of how you should and how you shouldn't use it. In most cases the typical constructs of structured programming are preferrable, but not in all.
If you really thought the arbitrary jump "has a place in any language" you would not use basically any languages from the 1980s onwards since they all neuter this feature for a good reason as the article explains, and some of them do away with it altogether.
Even C++ - a language that has never seen a gun it won't supply loaded and pointed at your feet - does not allow you to goto labels in other functions, and will run the necessary constructors/ destructors when you enter/ leave scope with a goto statement.
Apart from the TFA covering a particular python lib, I'd like to point out how the Go philosophy worked before. Given:
Situation 1: "the proposed style of concurency is available in go" so let's have a free ride and we can have linters and human reviewers trying to catch all the concurrency bugs faster than contributors are inserting them. /s
Situation 2: the proposed style of concurrency is the only one available in the language.
Approach 2 would make sense.
Completion is just a type of cancellation.
Spawn 10 workers to lookup Dog in 10 different dictionaries, the first one to get the answer wins. This is hard to do with out language/runtime cancellation support.
Note below is a practical lib to get close to this https://blog.labix.org/2011/10/09/death-of-goroutines-under-... .. https://github.com/go-tomb/tomb/tree/v2
It is trivial if the workers can communicate using a shared flag that represents "Dog is found."
To get a better sense of go there are five essential concurrency features:
1. Go statements are a nice syntax to run background micro threads (as mentioned in this article)
2. Go Channels pass messages across those threads as fixed memory queues and powerfully as you add items to the queue you block until the item is added (the second part, blocking on add, is very powerful as it prevents the flow of concurrency from infinitely filling queues that are never consumed! There is more to go channels that is possible with fixed memory buffering to prevent the block, but that blocking is key to consider!)
3. Go Select Statements (not switch statements!) let you watch concurrent queues at once in a thread safe way. These are essential for using channels properly and they help manage almost all channel flow (consumer thread progression, error handling, done detection, etc)
4. Go Context objects let you cleanup background threads based on multiple criteria server errors and timeouts being the most common. The best hint you are in a concurrent-friendly function is usually that it passes context as an argument for cleanup purposes.
5. Go wait groups let you wait for all the go statements spawned to finish before proceeding (simple, but essential at times)
I know it’s hard to learn the entirety of a langue without using it daily, but I encourage people to try out go to experience these five parts together. Go is truly excellent at expressing some hard concepts well. That doesn’t make it easy — concurrency isn’t easy — but it is easier with go constructs than without.
That's literally the opposite of what the article says. Which btw isn't about Go specifically, but about concurrency in general.
Go Statement Considered Harmful (2018) - https://news.ycombinator.com/item?id=26509986 - March 2021 (82 comments)
Notes on structured concurrency, or: Go statement considered harmful - https://news.ycombinator.com/item?id=16921761 - April 2018 (230 comments)
"Considered Harmful" Essays Considered Harmful https://meyerweb.com/eric/comment/chech.html
Took me a while to get it — child processes belong in nurseries. Bad abstraction, because the key here is processes. Lots of thing haves child nodes.
And what happens in nurseries? Growing? Maybe they were thinking watching — babysitting and it’s a cultural terminology difference.
But it would be just as silly to call a thread monitor/manager a babysitter as a nursery.
Like I said, it’s a great concept and a valuable abstraction, but I fear it will need a better name to take off.
Abstractions have nothing to do with their names. They are not good/bad based on what they are called. You might be conflating metaphors/analogies with that.
Pretty sure "sync.WaitGroup is too hard to reason about" is not a real issue people are having.
AFAIK most of the challenges occur within that structured block, so to speak. Robust communication between concurrent processes is the hard part, not managing their basic lifecycle.
- you can cancel them
- you can pass a pointer to the operation from places to places
- you can set dependencies between operations so that one doesn't start until another is finished
- you can set its execution priority (on the queue)
Syntax may not be the best, and there may be a few problems with encapsulation (an operation can do any kind of memory manipulation), yet i keep getting back to them whenever i have to do serious and robust work.
AFAIK it's a very popular and active library still.
My (rust) code using Tokio starts a bunch of tasks in main that live for the entire lifetime of the app. They’re independent and communicate over channels with each other – and possibly the outside world.
Hard to see what problems this causes that Trio can fix. But maybe I’m zooming in on the wrong use case?
It doesn't sound like you need it for what you're doing.
Just quickly running a task to perform a handful of stuff concurrently for a single purpose (like doing a few network requests and packing the results) is hardly where I encounter big issues. The compositional behavior of Futures really helps here I think. A bunch of `Future<Result<A, Error>>` go a long way.
I actually have found rusts futures/results to be more cludgy than scala, were I could flatmap in a fairly nice syntax provided I was fine with using transforms.
Do you pass an early cancellation variable to your future returning rust functions?
I wrote a userspace M:N scheduler which multiplexes N lightweight threads onto M kernel threads. It currently preempts lightweight threads and tight loops round robin fashion but I could implement channels between lightweight threads and implement CSP.
I created a construct for writing scalable systems concurrently called Crossmerge. It allows blocking synchronous code to be intermingled with while (true) loops and still make progress and join as a nursery does. There is a logical link and orthogonality between blocking and non-blocking and sometimes you need both in the same program.
https://github.com/samsquire/ideas4#118-cross-merge https://GitHub.com/samsquire/preemptible-thread
I added a multiconsumer multiproducer RingBuffer ala LMAX disruptor to the M:N thread multiplexer and it handles IO in a separate thread. If I add epoll and io_uring I could also handle asynchronous IO.
My goal is to add an LLVM JIT and then I have an application server.
I write a lot of concurrency and parallelism in ideas4
HTTPS://GitHub.com/samsquire/ideas4
This is a lot of why he goes into the history of "old-school goto" and its problems in the post. One of the issues with "old-school goto" is that you could never be sure if you called into a function whether it would actually return out of that function, or end up "goto"-ing somewhere else completely different, without going into it and inspecting it. Similarly, one of the issues with calling a function in Golang is that you can't be sure it didn't spin off a goroutine which is still doing some random work or other.
I mean, yeah, you shouldn't just randomly fork off a goroutine which retains references to state passed into a function without clearly documenting it. But there's nothing to stop you from doing it.
And the crucial point is that because you can do it languages have to have weaker guarantees because they have to assume you could do it.
This is a good article for sure. But it's just my opinion that Martin Sustrik who originally coined the term structured concurrency explained the concept better than this article at much better depth https://250bpm.com/blog:71/
Q&A's like this have contributed to me avoiding Go.
Goroutines are purely managed by the Go runtime in userspace. They never ‘just disappear’.
I can't speak to the accuracy. I didn't imply that the answers somehow affect my opinion of Go, but both the questions AND accepted answers.
Somehow Go managed to release with a fork that was worse than PHP's first stab, and that's impressively incompetent. Goroutines are the same as js promises without the native state management...and the detachment of declaration and startup? Jesus that's prone to abuse/bugs. Coroutines are a horrific display of the base language on their own. Yes you can create a custom/library wrapper, but that's a leaky abstraction, at best.
There are things to be admired about Go's choices, as a language, but there is enough to deride that I avoid bothering to even toy with it.
It seems to be a safe pattern under the criteria stated in the article as long as all async calls are awaited. This pattern guarantees the flow will return back only after all async task have finished.
The article says modern languages allow domesticated forms of goto (statements like break, continue, return...) that are scoped at function level. What about exceptions and exception handling? An exception thrown in a function and caught in a parent works as a wild goto. The railway pattern comes to my mind.
> It seems to be a safe pattern under the criteria stated in the article as long as all async calls are awaited.
Which means it's not unless that awaiting is mandatory in all cases.
Which it is not because pretty much all such systems have a `spawn`-type construct (when it's not the plain default as it is in Javascript, or C# IIRC) which just forks off an independent task. Your `await` acts as a `join`, but that's still just a join, which is optional, and which most systems have (except go, because goroutines don't have handles).
The argument of structured concurrency is the binding of mandatory joining (or awaiting) to the lexical scope, in the way structured flow bound jumps to lexical scopes.
At least in rust, calling an async function won't do anything by itself. It must be spawned or awaited. However, I wouldn't be surprised if other languages spawned on every async call and the await was just a join handle.
https://blog.labix.org/2011/10/09/death-of-goroutines-under-... https://github.com/go-tomb/tomb/tree/v2
Exceptions? :p
With return you can jump only 1 level higher at once
Or perhaps by the wildly popular Communicating Sequential Processes by Hoare in 1985 (the 3rd most cited thing in Computer Science for over 20 years after publication) which called the control brackets "cobegin/coend" in Hoare's section 7.2.2. [1]
[1] https://en.wikipedia.org/wiki/Communicating_sequential_proce...
Edit: I see someone else noted this below. I had always assumed that golang's concurrency model was somewhat influenced by Occam, via ALEF (Phil Winterbottom).
I wonder if we just ever come to the conclusion that doing many things at once is difficult no matter what we do - at least if there is shared data involved...
When this pattern applies, it is indeed easier to use than less structured alternatives and error handling & resource clean-up & API design are perennial topics, but I'm not sure we need even more diverse terminology. For example, what the article dubs "nursery", most call a "pool" or "group". "Nurseries" are declared a new thing in a boldfaced paragraph with innovation claims only softened later or in footnotes. I think this is why a lot of pushback happens, but also see the funny [2] mentioned elsethread [3].
I did love the domesticated-wolf comparison pictures, though. :) (And I say that earnestly, not snarkily.)
[1] https://en.wikipedia.org/wiki/Fork%E2%80%93join_model
You get all of these things with the simplicity of uncolored functions, plus additional guarantees and customizability about blast radiuses of crashes.
I've been seriously turned off from go (after dedicating years of my life to it :(). It is fundamentally flawed IMHO, a house of cards built on quicksand.
I wonder what we'll think of GO in 5, 10, 25 years. Within 50 years I kinda doubt many humans will give a crap about it at all.
The answer, for me, is always channels. What you put around the channels is the challenging part.
Channels are built to pass information between goroutines. If you are doing this via any other signaling, just don't. You can loop over channels for long running sequential reads, you can test them to see if they're ready to read or ready to write.
Honorable mention to context as well, extremely useful structure.
"Data Race Patterns in Go", posted 21 days ago: https://news.ycombinator.com/item?id=31698503
Even though I'm extremely careful, I'm sure I've done one or more of the anti-patterns they outline where the outcome is completely incorrect program behavior compared to my intentions as the architect of the program.
A good language wouldn't encourage or even compile with such nonsense.
---
Isn't it funny how Go offers channels but the stdlib never uses them at all?
go/src $ grep -r 'chan ' | grep -v test | wc -l
402
go/src $ grep -r 'Mutex' | grep -v test | wc -l
362About 80% of these problems can be covered with new linter rules. Go as a language already strongly depends on linter rules. I mean, there are a few must-haves already, and adding a few more won't make much difference. This isn't optimal, but it's not a deadly flaw of Go ecosystem.
Remaining 20% need solid test coverage (using -race). You are right, these absolutely need attention from Go language creators/architects. In their terms, these kinds of promises which shouldn't have been made for v1.0.
It doesn’t similarly expose mutexes that package clients have to fiddle with.
I think I understand the gist of where the author wants to go, and I do agree that nurseries sound like a good idea. From observing myself and people around me, I think people learn Go (concurrency) in several phases. I won't be so arrogant as to presume I understand how to always structure goroutines and channels correctly, now. But looking back it was "easy", then it got harder, then it got easier again as my understanding of how to structure things evolved. But I won't say that it is ever easy. Concurrency isn't easy. And it is important to keep in mind that stuff that is supposed to help you won't necessarily make everything easier. Concurrency is still fundamentally hard.
The hard bit is to actually design this idea in a way that doesn't make Go ugly or which creates bifurcations in how you use the language. If something causes a bifurcation I would actually claim that it isn't worth doing. There is value in leaving languages alone rather than complicate and potentially make them messy. Languages become harder to use when you have to start deciding on what parts of the language you want to use. Adding stuff to a language with established practices is much harder than designing a language to begin with.
Also, syntax matters. I didn't actually mind that Java involved a lot of typing because the syntax wasn't that complex or particularly ugly. It wasn't hard to grasp when reading. Just horribly verbose. But comparing how people I met thought about Java in relation to other languages taught me something important: a surprising number of programmers live at the surface, only caring about syntax, and don't actually understand what the syntax really does.
If someone can implement the idea I'll have a look. But if it complicates, bifurcates or makes Go exhibit less developer empathy, it probably shouldn't be inflicted on Go. Perhaps it can be applied elsewhere.
And I actually have a recommendation for where to start: scrap the posting and attempt a concise description first.
- nobody uses semi colons, that's a huge red flag because the tooling will literally remove these symbols from your code, did you even run any go code? clearly not
- goroutines are not threads and galloping past that obvious chasm is also telling: you're not really sure what these magical things are but, somehow, you know they're bad. this is a flawed line of reasoning that was never going to convince me
- because you don't know how goroutines and the userspace scheduler work, you skip over all the benefits they provide and thusly nurseries give me nothing than a hand holding experience less effective than the existing tools I have. Thank you for wasting my time because I was genuinely holding out for _any_ kind of empirical reasoning. My mistake.
- As proof of the author's research negligence: Not a single mention of channels. Not one. Homework was clearly not completed
I'm all for debating a language's efficacy and tradeoffs, but not when the opposing side has no idea how anything works. Then it's not a debate, it's just the ignorant proclaiming a need to interfere with others. Go away, please.
- If you’re not using channels because they are slow, now you’re letting some nebulous “context” bleed into every function to handle closure and cancellation. This is basically provided implicitly by the nursery concept, but stapled on to every function in go because it was an afterthought, then google started using it, so it’s everywhere.
- The Unscoped nature of go routines does make the program more complex to reason about.
This is about contrasting structured vs unstructured concurrency. The language, the threading model, how threads communicate and coordinate ... none of them are germane to the issue.
Wherever you have a fork without a join in the same scope, it is unstructured and gives rise to some concurrency issues.
Structured concurrency promotes composition, similar to ordinary function composition. For ordinary functions, the caller's control flow is logically blocked from proceeding until the callee is done. Similarly, in a structured concurrent setup, a function is logically blocked from proceeding until the tasks it spawned have finished and returned to the spawning scope. This makes it easier to reason sequentially. "finish doing a bunch of tasks, then do this, then do that" etc. The key word here is 'finish'. Not 'spawn a bunch of tasks in the background'. One can then reason about the effect of the function and all its nested tasks as a single unit.
The most elegant example is Occam, where SEQ and PAR are language constructs. (For those interested: http://www.transputer.net/obooks/72-occ-046-00/tuinocc.pdf)
2. Inferring that the author doesn’t know what threads really are when they could just be using slightly different terminology than yourself (i.e. terminology where “threads” are not narrowly defined as “OS threads”)
3. Just based on the bad inferrence in (2) + complaining about they did not appreciate goroutines enough + complaining about “hand holding”
4. Proof that the author is incompetent: they didn’t even mention this one particular concurrency construct. Cherry-pick ergo preconceived conclusion
Unsolicited inferrence by myself: peeved that the author said that `go` was harmful—even though the author also said that this is a general problem—, and thus you needed to concoct some half-assed arguments in order to justify making a reply.