196 points · by ibobev · 1y ago · 102 comments
Seems rather like an very incomplete view of a C++ programmer, wanting to raise it to "systems programmer".
Immutable is kind of irrelevant in a discussion of multi-threading because immutable data has no problems in this regard. Which, of course, in a way also makes it relevant because one prevents issues. Ultimately one cannot have just immutable data because the computer would not be allowed to do anything. This document would be about data that cannot be immutable.
But the complaint sounds a bit like an article about assembly language getting the complaint that it does not explain how to implement a word processor.
To push back on this, no data is completely immutable, it is mutable on initialization, treating it as immutable between threads is ok after this stage, but if you disregard issues with timing and mutation you will run into problems between threads on initialization.
You need mutation or garbage collection (and systems programming is the kind of environment where that's not just "someone else's problem").
The point of this article is to detail needs for those monads to interact in a concurrent manner.
I'm not sure I understand this comment. C++ is one of the very few languages that can be used for programming everything from a web server to a garbage collector to firmware. There's no "raising" going on here.
Presumably, you're thinking of systems in the more abstract sense: systems of more or less pure software components that model some domain. That's just not what this article is about.
You could absolutely get a job as a system programmer not knowing and never touching C++, but not knowing Shell will not get you anywhere in that field.
It doesn't really have to be direct or tight (not even sure what that might mean). I'm guessing you were trying to say that it has to have minimal overhead compared to theoretically possible performance, in which case that's not true at all (a lot of Linux services and management tools are written in Shell, which just isn't known for great performance at all).
C was the overwhelming language of choice for a very long time, but C++ made steady and verysignificant inroads in the last 20 years. Objective-C and Java had/have niches. Rust and Go have traction and continue to gain more. Swift is working towards it.
Actors and immutable types, which the GP mentioned, have less signifance here because they largely trade transparent resource management (which is critically important in many of these projects) for correctness guarantees and sophisticated domain modeling. That said, we can expect there to be more room for them, especially where implementations of those features are zero/low-overhead.
As far as mentioning shell and Python, I don't consider those primary system programmer tools. You might need to know them to be a good generalist *nix system programmer, but it's really tangential to whether C++ has a place in systems programming. Python and shell are in competition with Perl and Tcl, not with C++. To say that they are is like saying a carpenter is in competition with a welder because they both build stuff.
[1] Which is not to say "best". My standard complaint in these threads is that the C++ ordering semantics are a mess designed to make things easier for compiler writers to target architectures with variant ordering guarantees and not for algorithm developers to create correct code. But lockless code is much harder to write than compilers! It's a bad trade. ARM had this right decades ago with simple read/write barriers, which are vastly easier to understand when reading code.
One of the interesting problems for Rust-for-Linux is what to do about that, Rust has all of the C++ 11 memory ordering except the problematic (and in practice abandoned) Consume ordering, but it doesn't have a convenient way to admit a different model, yet Linus isn't exactly likely to wake up one day and declare now Linux has the C++ 11 ordering model.
As to your concern, of course the compiler vendors have to worry about portability. It's all very well to say this works on ARM, but the expectation from a person writing Rust or even C++ is that a correct program should work on all of an ARM, an x86, archaic PowerPC and somebody's cheap in-order embedded CPU.
If the vendor only really cares about one architecture (cough, Microsoft) then they might invent weird rules that only really make sense for that architecture and your "correct" programs either don't work, don't compile, or are very slow on every other CPU. But that's hardly a reliable way forward into the future.
Yes, but the point was that "defining a language that doesn't suck" is a competing requirement. Again, C++ just dropped the ball here and solved the wrong problem. And we all suffer for it with repeated blog posts like this one trying desperately to explain exactly what "acquire" means and not how hardware actually works.
And yes: Linux has clean and easy (or as easy as these things get) read/write barriers, the implementation of which has now been terribly polluted by the toolchain's incompatible choice of semantics.
The x86 is the weird architecture that tried to keep existing programs working when they moved to multicore. Most other architectures implemented whatever is easier to implement in hardware, and compilers have to target that. And the compiler can't simulate a strong memory model on top of a weak one, because that means lots of overhead for every memory operation and that's not what C does.
The acquire/release semantics make perfect sense for locks, because that's what it was designed for. Designing anything else with them is extremely difficult, and in practice such work tends to lean heavily on the full-barrier "sequentially consistent" primitive instead. The older read/write barrier instructions were much simpler. (And x86 is simpler still, with just one reordering rule to worry about and a single idea of serializing instructions to regulate it).
The term "systems programmer" is right there in the title. They are also the very first words in the article. The examples are in C++, but the whole document focuses on both C and C++. The article clearly focuses on the primitives, as it should.
It's undoubtedly a great article on the subject, but nitpickers have to nitpick, and one-uppers have to one-up.
I look forward to read your article on the topic.
Russ Cox in 2021 offered a higher-level insightful history of evolving hardware and software support for concurrency, discussed just yesterday
https://news.ycombinator.com/item?id=42397737
His take (as I take it): systems programmers should only use sequentially-consistent atomics (and only via well-tested concurrent data structures).Easy peasy! ;p
The argument goes roughly like this:
If you don't offer a default here, the programmer who supposes that the answer to their question is atomics will be obliged next to figure out which Order they wanted. Or they could give up and say "I need a grown-up". Because C++ chooses to offer Sequentially Consistent as the default that programmer will presume this must mean it now does what they naively anticipated. Russ' overview might suggest that's true too.
Here's the problem: It may not do what they wanted, it may be that no ordering rule would achieve their actual goals, but since they weren't asked to go read the ordering rules and pick one, they never confronted this awful problem, and are instead blissfully unaware. They are strolling into traffic knowing that they've picked the best possible road crossing rule and not aware that in fact no possible rule could make crossing this Interstate on foot safe to do.
Here's another bad problem: If it does achieve what they wanted, it's probably overkill. The only reason programmers should reach for atomics is that the provided facilities which were safe for them to use didn't deliver the performance they need. But the Sequentially Consistent ordering may hurt their performance, injecting barriers they don't need, using slower instructions or even stalling when that was unnecessary. If they'd read the rules they might for example have realised they only needed a Relaxed ordering - much better, or that with a slight tweak they can use Acquire/Release.
Once you start thinking about a program as a sequence of loads/stores (i.e. reads/writes to shared memory) and note that Pipelining/OOO/Superscalar are techniques to parallelize these (and other) instructions for a single thread of control you start getting an idea of how sequential order can be preserved though the actual execution is not quite so. Now add in another thread of control on another core and you get the idea of Memory Consistency problems and can be introduced to various "Consistency Models" (https://en.wikipedia.org/wiki/Consistency_model). Next introduce caches in between and you get "Cache Coherence" problems (https://en.wikipedia.org/wiki/Cache_coherence) Walk through a simple example like "c=a+b" in thread1 and "z=x+c" in thread2 and observe the interleavings and possible problems. Now move on to "Atomic Instructions" (https://en.wikipedia.org/wiki/Linearizability#Primitive_atom...) and how they can be used to implement "Locking" (https://en.wikipedia.org/wiki/Lock_(computer_science) ). Finally show "Memory Barriers" (https://en.wikipedia.org/wiki/Memory_barrier) as a means of enforcing a checkpoint on memory operations. All these together should make an understanding of Concurrency clearer. One can then jump back up into the language and study the language primitives for concurrency management and their common usage patterns.
A formal education, in any domain, forces you to explore areas of knowledge that may not be directly applicable to immediate 'real world' problems. It does however give you the background to identify and explore those areas when you approach something that does overlap with work that people have spent literal lifetimes considering ahead of you.
I say this as someone without a formal CS education but has been working with computers for some time. I've spent countless hours, days, and months playing catch-up on that knowledge when I stumble into those blindspots.
Are you quite sure you understand the atomic primitives you're working with? Mara's book https://marabos.nl/atomics/ is pretty good, it's written in Rust but like, if you thought you needed a Memory Ordering that doesn't cover you're boned because your tools don't support that order (and probably in an appendix or footnote somewhere they admit that) either.
Reach for tooling to diagnose ordering problems. Loom and Shuttle are where I'd start in Rust, hopefully you have equivalents in any language you're using. Those are: A thorough tool which tries every possible correct interleaving and tells you what happens, and, a probabilistic approach which just picks at random and figures on average it should find the problem cases (but we can't prove it does).
When in doubt, steal: There is often a published, correct, algorithm for whatever you're doing. It might take an hour to convince yourself that algorithm is correct, but hey, you're planning to spend four hours on your algorithm which isn't correct, that's a bad trade.
Rubber Ducks are invaluable. If you feel awkward addressing an inanimate object I don't recommend using pets or livestock as both have no reason to be attentive, try a human who likes you. The important property of the rubber duck is not that they understand what you mean, after all a plastic bath toy can't understand anything, but that you will feel the need to make whatever you're saying make sense and in doing so may uncover a place where your algorithm is inconsistent.
A good book to study and get a handle on all aspects of Concurrent Programming is Foundations of Multithreaded, Parallel, and Distributed Programming by Gregory Andrews - https://www2.cs.arizona.edu/~greg/mpdbook/
Even Rich Hickey, when discussing concurrency in Java/C#/C++ said "I am tired of trying to get right, because it is simply far too difficult."
> In particular, talk about shared state, how we do it today, how you do it in C#, Java, or C++, what happens when we get into a multi-threaded context, and specifically what are some of the current solutions for that in those spaces. Locking, in particular. That is something I have done a lot of, over a long period of time, and I am tired of trying to get right, because it is simply far too difficult.
( https://github.com/matthiasn/talk-transcripts/blob/master/Hi... )
The second point to note is that when people like Rich Hickey or John Ousterhout talk about multi-threaded programming being "hard" they are talking about a level of depth far beyond what a "normal" application programmer will encounter in his/her entire career. These guys span everything from Apps/OS/Compilers/Language/Hardware and hence by necessity know the full gamut of complexity involved in concurrency. Trying to understand concurrency across all the above abstraction layers is very difficult and that is what they mean when they say it is "hard".
But for most application programmers the above is simply not relevant and they can comfortably stay at higher-level abstractions given by their language/library and ignore lower-level details unless and until forced by other needs like performance etc. One can do a lot with this knowledge alone and indeed that is what most of us do.
So instead of making wild statements like "random crashes and segfaults" and "too hard to program" learn to use heuristics/commonsense to simplify the code structure eg. a) copy code patterns given by reputed authors so one does not make unnecessary errors b) Keep the number of locks to a minimum by using a few "global locks" rather than a lot of "granular locks" c) Learn to use Thread Local Storage d) Acquire locks/resources in the same order to avoid deadlocks etc etc.
These three have different memory models, concurrency primitives and adopted practices...it's odd that they are lobbed together.
I strongly dislike the term "lock free", which is really just a marketing term invented by people trying to promote the idea that some algorithms are better than those "lock-based", when in fact those "lock-free" algorithms were only choosing a different trade-off in performance, which can be better or worse, depending on the application.
Even worse is that after the term "lock free" has become fashionable, it has also been applied to unrelated algorithms, so now it has become ambiguous, so you cannot know for sure what is meant by it, unless more details are provided.
When accessing shared data structures, the accesses are most frequently done in one of three ways.
The first is to use mutual exclusion, when the shared data structure is accessed within critical sections and only one thread can execute the critical section at a given time. This method is usually called as lock-based access.
The second is to use optimistic access, when the shared data structure is accessed concurrently by many threads, but they are able to detect interference from the other concurrent accesses and they retry their accesses in such cases. This is what is most frequently referred as "lock free" access. Compared to mutual exclusion, this access method may be faster in the best cases, but it is much slower in the worst cases, so whether this is a good choice depends on the application.
The third method happens when it is possible to partition the shared resource between the threads that access it concurrently, so their concurrent accesses can proceed without fear of interference. This partitioning is usually possible for arrays and for buffers a.k.a. FIFO memories a.k.a. message queues (including one-to-one, many-to-one, one-to-many and many-to-many message queues).
So your "lock free ringbuffer" refers to the third method from above, which is very different from the "lock free" algorithms of the second kind from above.
Whenever concurrent access to partitioned shared resources is possible, it is much better than accesses with mutual exclusion or optimistic accesses, which require either waiting or retrying, both of which are wasting CPU time.
Therefore using correctly-implemented message queues or other kinds of shared buffers is usually the best method to achieve high levels of concurrency, in comparison with other kinds of shared data structures, because it avoids the bottlenecks caused by mutual exclusion or optimistic accesses.
Step 2: when you absolutely need concurrency within one app, try using some library that already solved the issue. For example, there are lots of databases with pretty strong concurrency contracts while still being efficient.
Step 3: if you absolutely need custom solution, use a library/language that provides reasonable tools out of the box and keep your logic to minimum.
Following the first two steps will solve 95% of your concurrency issues, if you include step 3 it goes to 99%.
So it was left to the developer. It is much better now but for so long the problem was ignored and now we have decades of 'not sure if I can touch that code'. Also by default C/C++ are fairly open about sharing memory. So it is very easy create race conditions on memory. It would be nice if the base language had a concept of 'locked to a thread' or 'i want to share this with other threads' then the compiler can flag where I have wandered into the weeds for a class so we could catch the race conditions at compile time, at least some sort of warning.
Sharing semantics were awful for a long time. stdlib has done some very good things to help clean that up but it is still very easy to share between threads and cause yourself a headache.
The problem with an owning mutex in such a language is that you can (on purpose or by mistake) keep accessing the thing it owned after you've released the protecting mutex. Rust's Mutex<T> owns the T but it has the behaviour you want where if you tried to keep the access to T but give back the mutex that doesn't compile. "I tried to unlock the mutex but I still need it, d'oh".
And the same problem applies broadly, you should not share write access to things without an ordering guarantee, but it's hard to ensure that guarantee is followed in C++.
[1] https://bholley.net/blog/2015/must-be-this-tall-to-write-mul...
https://github.com/mrkline/concurrency-primer
You can fork/clone/download the repo and then convert the ebook into Kindle or epub with Pandoc, like so (this is what I run):
pandoc -o concurrency-primer.epub concurrency-primer.tex
(I can share my converted file, but I don't know which file-sharing service is permitted on HN. If anyone can give me suggestions on this, I will be happy to upload it and share my epub file.)
I had a couple of those. (Well, still do – but not using them for anything now. Mine are the ones with 16 cores, that I got for backing them on Kickstarter when they did their original crowd funding) And I was wondering the same a while ago. This guy that was part of Adapteva, makers of Parallella, is working on some ASIC stuff now it looks like.
https://scholar.google.com/citations?user=qdDUg48AAAAJ&hl=en
And since Adapteva website also says: “Adapteva is now Zero ASIC”, I guess maybe some other people that were originally doing the Parallella thing are now doing ASIC things with that guy too.
The Parallella website is still up.
And you can download the old Ubuntu images for the Parallela SBC from the GitHub releases. But they stopped adding anything new to it years ago.
They will also often work with lower-level abstractions, such as threads, so that the higher-level developers need not think about them in their own designs.
A person who writes software that is closely bound to the operating system interface and/or hardware for reasons of performance and/or functionality.
To give you some examples: you might be working on an SDS product (software-defined storage), perhaps a filesystem, or maybe a network-attached block device etc. that operating system has a way of interacting with and exposing to other software as it's own service. To make it even more concrete: you can write a filesystem in a way that it interfaces with Linux kernel, and, once installed, users will interact with it through VFS interface (so, they don't even have to know they are interacting with your specific product). ZFS is a good example of this kind of software.
Similarly, it could be SDN (network), eg. various VPN software s.a. OpenVPN. Or a users / permissions management software (eg. LDAP server, s.a. slapd). Software to manage system services (eg. systemd). Software to manage specialized hardware (on top of drivers) that, again, provides its services through the operating system (eg. nvidia-smi). Or, maybe it's a software that manages memory, terminals, virtualization, containers (eg. DMA over IB, tmux, QEMU, containerd).
Sometimes this category is extended to system monitoring or higher-level management tools that still give some kind of general service similar to the one provided by the operating system. Think about SAR or mdadm kind of tools. Or, this could also be testing of operating system services (eg. FIO).
Sometimes, this can also mean some kind of administrative tools that perform either more high-level management of operating system (eg. yum, the RHEL package manager), or management of groups of operating systems. Cloud tools can fall into this category (eg. boto3 AWS client). But, this is kind of stretching the definition.
----
So, as per usual in the field of programming... we don't have an authoritative source and a definition for a widely used term. You just have to accept (at least for now), that different people mean different (but often significantly overlapping) things when they use the term and ask more questions to refine what they mean by it.
completely stolen :)
In the before times the terminology came from system 360 and descendent mainframe systems where the system programmers tended to be intimately involved with the deployment and programming of the operating system and associated "exits", and such tasks tended to presume some working knowledge of assembly language (operating systems were very crude at that time...and many shops tended to "customize" them if that makes sense...you would sometimes have serious problems with operating system level things and at that time the generic response would be "contact your systems programmer", who would either fix it or get in touch with IBM...so TLDR is basically a sysadmin that is good at assembly). Big companies could afford to have systems programmers on staff and needed them because every shop was different and computers were very custom and crude at that point in history.
That's where the terminology came from originally but now it has expanded and can mean different things.
The "systems programmers" terminology was mainly just a differentiation from the more generic "application programmers" (who would probably program in COBOL or something similar, doing business related tasks) or "system operators" (who would not usually be programmers at all, and would do a lot of what we would now consider sysadmin work).
Nowadays it just means anything that isn't bog standard CRUD or frontend web app stuff. The terminology has evolved but has a somewhat similar meaning to when it originated. It's tough to understand exactly without the historical context which is why I have included that.
For obvious reasons, this has some overlap with the more modern definition of "programmers that build systems that other programmed then use". Because the application programmers on those mainframe systems would be relying on the systems programmers to not screw up their assembly wizardry or else everything would fall apart.
So "devops" existed even in the mainframe era! :-D