122 points · by kiyanwang · 6y ago · 131 comments
In my experience, simple concurrency is easy. Confused concurrency is exceptionally hard.
I think about this in the same way I think about C++. C++ is quite nice, if your teams limit themselves to a reasonable subset of the language. But it can become an absolute monster of cumbersome complexity, if these guardrails go away.
Concurrency feels the same. If you take a certain view on concurrency, which is "do it as simply as possible, don't break certain rules, don't try to be too clever," I find it fairly straightforward to reason about.
At the same time, 9 out of 10 of the hardest things I've debugged have always been nasty, awful concurrency bugs. The reason it was so hard? The concurrency was complicated, interwoven, assumption-laden, and absolutely impossible for anyone to reason about. Implicit contracts between calls required entire whiteboards of non-trivial state to understand, and even then, with all that work, it was a needle in a haystack.
I guess I would just say: It doesn't have to be hard. It's only hard if you don't respect it from the beginning.
The task at hand wasn’t easy at all, it required both:
1. Making numerous network requests (some endpoints support batching, so do that as much as possible) 2. The entire main loop needs to be as fast as reasonably possible
The only real way to satisfy both, given that serially executing the network activity would waste tons of time, was some fairly tricky concurrent logic. I ended up using a few queue structures to collect day before making batch network calls, and stitching together all of the results at the end (block on all work threads, collect, report, then start next iteration)
Every step along the way made sense, every addition of complexity felt justified. And the first person to come to me asking how the fuck it got so complicated is frustrated, so my knee jerk reaction is to get frustrated back saying well how else could we satisfy complex requirements with a complex solution.
We should always be challenging ourselves and others to keep solutions simple, but remember that the simplest solution may itself still be complex.
Otherwise when the logic gets complex I try to model it as independent threads each having a well-defined role (e.g. exclusive write access to SQLite) communicating with channels. Although I tend to code these things in Rust, the language who taught me that philosophy is Go.
Design-wise:
The IO multiplexing — event loop(s), the completion callbacks go to the "Processing".
Processing — usually beneficial to model as a processing graph (tree/pipeline being specific examples of a graph without feedback loops). It's a clean, low overhead abstraction, easy to visualise (and thus discuss with others), easy to change structurally or in the "aspect oriented" way.
Examples in JVM world: Netty pipelines, AKKA actors, streams, and graphs, in C++ world ASIO & its executors sub-framework.
Queues/Threads is still a sufficiently low level to comfortably operate on.
group -> make concurrent calls and wait -> sort
which would have been very straightforward, and probably faster too because you don't let any one step interrupt the other
One needs to pick the concurrency model and design up front. Document it before writing a single line of code. Then stick to the plan. It takes discipline, but it's not difficult.
I mostly write in C with pthreads and as long as one is willing to apply discipline to the task, there's no reason to fear concurrency.
If one starts adding a thread here and a mutex there and some shared structures over there without any prior plan then yes, absolutely, that leads to a world of hurt and a deep hole that is very difficult to get out of. So, don't do that.
This has to be a universal rule of programming. It's equally true for Ruby and Perl, which are extremely effective languages, but devolve quickly because of their uncanny ability to power cleverness. It's the whole premise of Go, by being boring by design.
Complex is easy, simple is hard, but it seems mostly because we fail to be able to resist the allure of cleverness.
Yes Go the language is boring and I like this idea, but the runtime is a black box, that I don't like so much.
[0]. For example: https://github.com/golang/go/issues/14592.
Document first, code later. Makes nearly all problems easy.
Jumping to writing code first is a future disaster in the making.
Write the specification as code - make sure it's something that can actually be checked. Then you'll know whether it's actually any good.
There is nothing wrong with prototypes but some people mistake them as production ready items because it looks like a whole load of work has been done.
Some things do have to be designed, and not just thrown together though. That may be through spec, but it could also be working things through on paper. Concurrency is certainly one of these. Other things need to be iterated on in code. I'd hate to play a platformer where the movement mechanics were specced out by a comitee before any code was made.
Do you mean a written spec, or a proper formal specification?
It's not that react, redux and cie are something new or disruptive. It just enforces a set of design rules that turns a lot of concurrent inputs and outputs into a linear workflow.
I’m not sure I know what you mean by that.
> If you take a certain view on concurrency, which is "do it as simply as possible, don't break certain rules, don't try to be too clever,"
Is there a list of those rules?
Several different lists. You have to pick a concurrency model. Within that concurrency model, you pick some set of rules to follow which has the guarantees you want.
All of those things mentioned in the original reply is vague, and can only come from having experience in the subject matter.
That's why concurrency is hard.
There is just SOOOO much that can go wrong. But one general rule crystallizes itself pretty quickly:
DO NOT EVER MUTATE STATE!
I.e. when you write concurrent code that builds on state mutation, you are opening Pandorra's box. If you want concurrency that people can understand and maintain, write immutable, functionally pure code (same data in, same result out, no exceptions). That is relatively easy to police and enforce, while still flexible enough to solve most use cases. It may however, not be the most performant.
This is counterproductive.
Mutating state is by far, the most efficient operation on the computer. Copying state means (usually) calling the memory allocator, which (usually) must be done in a sequential manner. There are optimizations to allow memory-allocation to occur in parallel, but... things start to get inefficient (use of thread-local storage, which makes many pointer-indirections, etc. etc.).
-------
Why do people program parallel code, despite its overwhelming complexity?
Simple: to be faster. That's it. Its an optimization, arguably premature, but the programmer reaching for the "parallel" button is going for optimization for a reason.
------
Sequential code with state-mutations could very well be more efficient than parallel code with tons of unnecessary copies. Registers are fast, L1 cache is fast, etc. etc. Doing an operation, then undoing it (entirely inside of register space) is so incredibly fast, it will make your head spin.
-------
1: Write code.
2. If code isn't fast enough, single-thread optimize it. This usually means mutating state in an intelligent manner.
3. If code is STILL not fast enough, multithread it. You make a copy of the state, and then have multiple threads (each with their own copy of the state) doing... whatever you're trying to do.
Really? I mean like pretty much every instruction has separate source and destination addresses/registers, memory caches obviously complicate things, but it seems that processing data from one location to another is the most efficient operation.
> Copying state means (usually) calling the memory allocator
Sure, I guess if the main conception of moving data around involves not really knowing where it needs to go, and having to figure that out, that's somewhat true. But there are many ways to structure computation that minimizes or avoids allocator usage.
> unnecessary copies
I think this is the issue, if you have to copy first then do in place mutations, of course it'll be slower, but you can instead structure your entire computation to process your data from one location to another, then all your points about registers, and L1 cache being fast, holds true while still being able to handle immutable data
Unless performance is a problem, don't ever mutate state.
Mutating state is what computers are all about.
You can be super inefficient about it by copying everything on every operation. But avoidance is not the road to optimal solutions.
Fork-join is the simplest methodology, and supported in a very wide number of languages. In fact, its so stupidly easy, you probably are going to over-think it the first time you use it.
1. Fork when you need concurrency (aka: speed)
2. Join when you need consistency
That's it. Don't write mutexes, don't write barriers. Just join. That's all you need: if you ever need "synchronized" access, do it in the "single" or "master" thread, when all other threads are joined.
You _cannot_ have a race-condition if you only have one thread. Joins ensure that only one thread is running. What else do you want?
Fork-join parallelism has relatively low utilization. Its not the fastest approach, but its the "easiest" approach in my eyes.
------------
The #1 issue with parallelism books, in my eyes, is that we start with mutexes and threads, which are a very hard way to do parallelism.
I argue instead: beginners should start with easy (but inefficient) forms of parallelism, and then work their way towards complicated tools as performance becomes more-and-more of a consideration.
and then there was a follow up to it saying the measurements were wrong IIRC, and then a further article showing, more or less that getting your own mutex replacement correct is so tricky that for 99.99% of programmers, just don't bother.
If everyone is working in parallel, but on independent tasks, there are no issues.
You don't even have to share global state to work towards the successful outcome of some common objective. There are many problems that can be solved with actors operating in parallel with absolutely zero coordination between them. This might seem like its a place where only trivial cases live, but I have found some fairly complex concurrency scenarios that can be refactored into this trivial case by decoupling actors/state and reorganizing other parts of the system.
For example - Assume you were to develop a database engine that uses sequential integers for the primary key. You would probably have to develop a complex synchronization mechanism so that sequences are dealt out uniquely to concurrent callers. Or, you could sidestep the problem altogether by switching to GUIDs (V4 - Random) and allowing each participant to key its own entities. I feel these sorts of decisions should be considered as a primary measure before reaching for any form of shared state.
In other cases this is still easy. For example, when the ordering of the output doesn't matter. I'm dealing with such a case in a data conversion program.
A super simple example for when ordering doesn't matter is when you do parallel addition.
For example, a bank balance. Most people would assume that bank balances must always be correct. But this isn't really true. Back in the days when people wrote checks, your bank balance was almost never accurate -- it was on you to keep a local register and know your balance, and if you shared the account with someone else, to reconcile with them frequently. ATMs also use eventual consistency. When you take out $300 from the ATM, it attempts to update the balance, but it will let you take the money out if the bank is unavailable. Because the bank is willing to risk $300 that you aren't overdrawn. In most cases the "eventual" part is nearly instantaneous so you don't notice, but it doesn't actually have to be.
So the number one way to make concurrency easy is to avoid it altogether.
OTP underpins WhatsApp, Facebook Messenger, and Discord. People have been building very cool high availability embedded Linux projects using the Nerves framework. It’s very good for certain types of concurrent programs.
It won’t take over HPC simulation any time soon, but most of us aren’t working at Sandia, Oak Ridge, etc. Its great for systems that should naturally scale out but don’t map naturally to a GPU. For systems that want to scale up but are forced to scale out due to frequency limits, it’s not as good as C++ written with uArch in mind.
The difficult part I find with Elixir is that processes have a lot of roles: fault isolation, concurrency, synchronization, garbage isolation, maybe more. I've had projects where it's difficult to line these up - one design would be ideal for fault isolation, but it forces expensive copies to be made, so I can't use that design because it completely tanks performance.
Eventual consistency comes with it own set of counter-intuitives, and is a multiplier of possible states a system could be in. it is generally not a complication we would choose, but something we must cope with to do things that would otherwise not be feasible.
having lightweight isolated processes and no (or little) shared mutable state matters a lot. :)
For years, I certainly made my own share of concurrency horrors, in everything from C and Python to Java and JS. Eventually I (sort of) got it right in each, mostly by building up experience in approaching it the right way. But it always remained a source of easy to make mistakes (and sometimes near-impossible to solve complexities, with larger systems).
However, since working with Erlang/Elixir, I sometimes wonder what the F#$& I was doing all that time. Many ideas were certainly a bit challenging to wrap my head around at first, but once they clicked there (kind of) was no way back.
This will probably sounds arrogant, and it's okay with me if I get down-voted because of it. But the more I work with Erlang/Elixir (and a few others in the FP field), the more it becomes clear to me how much the languages I used to program in (and their typical challenges), now most of all look like a (rather sick) joke to me. Again, I know this might sound pretentious, if not offensive. But it is sincerely what I feel. In my defense: I'm not some kind of hipster, still wet behind the ears. I've been programming for nearly 3 decades and in well over a dozen different language. I'm one of those kids that were ripping apart assembly code of "protected" games and desktop software, and hacked around on micro-controllers, during the nineties.
While Erlang/Elixir may have shortcomings too (although I personally have not found any), it is one of the best things I've encountered for a long, long time. I'm also charmed by ClojureScript, but for totally different reasons. However, I do like it for when I'm forced to build something more complex for browser/front-end. But that's a whole different story, and not much relevant to this concurrency "issue".
That summarizes the problem with most of the articles and discussions on concurrency. People talking past each other because those who don't do much concurrency, especially complex concurrent software, haven't reinvented Erlang yet and don't understand what the fuss is about, and those who do can't explain in relatable terms how the actor model helps them organize concurrent code, preserve local reasoning, abstract, compose it, tolerate faults, etc. and eventually they stop bothering and so poor concurrency articles and comments continue to dominate the infospace.
Libraries and tools could replicate this in C++. A lot of people love erlang/elixir and have success with them, but I think it's a mistake to attribute it to the languages themselves and not the beam VM + the ecosystem around it because it misses the deeper understanding of concurrency techniques that work.
That’s why Java/scala’s akka is crazily complicated. They encourage you to use futures so you don’t lock a core! So suddenly you’re still dealing with concurrency but with even more complicating layers.
If you want practical guidance, my best is to avoid all of the concurrency constructs that are taught in schools. Use log-structured single-writer multiple reader, wait-free, processes and shared memory.
In both cases it takes a lot of hard work to learn how to not produce "dead-borns" or "genetically pre-disposed".
In both cases the course of "least resistance" (using intuition instead of logical reasoning) used by many as the default will most likely fail you. To develop an intuition of what is easy and what is hard with both system design and concurrency design is a matter of years of hard work of trial and error.
The actual question is why the complexity is so counterintuitive. I think this is to do with the Dunning-Kruger effect (the less you know the more confident you are).
In both cases the solution seems to be to keep beginners away from this and to have the same consistent, peer reviewed, approach across the system, and a process of improving it in a structured way. And of cause prefer higher level abstractions -> computation graph, pipeline, event loop, etc. over just hacking an ad-hoc Frankenstein out of low level primitives (which seem totally "simpler" if you ask a beginner).
With them and a basic understanding of single system concurrency, single system concurrency is and always will be trivial.
No mainstream languages give you a solid high level abstraction to build on. Some frameworks, kind of, do: ASIO in C++, AKKA Typed Actors and Reactive Streams and JDK CompletableFuture in JVM world, etc.
Shared mutable data concurrency is hard because it removes ability to locally reason about code.
x=1
x++
assert(x==2)
can now fail. x = 1;
assert(x==1); // May fail in a parallel worldIt has a delightful idea: to ensure the current thread isn’t preempted, set a global “lock” variable to true.
The scheduler checks “lock”. If it’s true, the current thread is added to the front of the threads list. Otherwise it’s added to the back.
Then the scheduler runs the first thread in the threads list.
So by setting “lock” to true, you are essentially instructing the scheduler never to switch threads.
If you like it erlang style: an agent can serialize changes nicely.
If you need coordinated changes, use software transactions.
Of course: next we'll introduce deadlocks with DB transactions. Fun!
Async is difficult I believe because "thinking" in inherently sequential because it is based on mentally reciting some (serial linear single-dimensional) language in our head.
An alternative could be some visual language where parallel and even 3D lines can be drawn. A mental image of it can be in our head. So I think async inherently needs some kind of visual language to make it easier to grok.
Saying that Go "adds even more complexity to concurrency" doesn't scan. It lets you write code using whichever model you prefer--CSP or mutexes.
It is definitely true that CSP is hard for many problems... but locks and shared memory is also hard for many problems. There is no silver bullet, so you need both.
Of course you can do whatever you want, but Go is a very opinionated language and there's an opinionated community behind it. Which it's fine. But then when you ask "how to do X using locks," the only thing people respond is the mantra of "don't communicate by sharing, share by communicating". Which doesn't help in any way. Then people ask complex questions about using channels and others say "why don't you just use locks?" That's why I think Go adds more instead of alleviating the complexity of writing concurrent programs.
I didn't quote that part because it's the most nonsensical part of the comment.
You've apparently been frustrated by your interactions with the members of the community and that's a fair complaint, but you haven't translated that complaint into a criticism of the Go language itself.
My experience is--CSP is a reasonable default, and "select" is a really nice language feature to have around, and mutexes / condition variables are still available when you need them. Mutexes aren't a good substitute for CSP and CSP isn't a good substitute for mutexes. You should have both available.
I typically use shared memory by default (mostly mutexes and waitgroups), and generally only use channels when I'm working with task queues, which is where they really shine.
No races aren't an inherent part of concurrent programming - you can make it safe.
> If it has to happen in a particular order, you can't do it concurrently.
I didn't say things had to happen in a particular order, just that their results are merged in a well-defined order. Otherwise you could test against one particular ordering that happens by chance, and then in production you get another order by chance that you didn't test against and it doesn't work! That's what you get with Go.