349 points · by rainbowgarden · 11y ago · 104 comments
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD00xx/EW...
Here is a implementation of P and V, the original counted semaphore primitives, from 1972.
http://www.fourmilab.ch/documents/univac/fang/
This is UNIVAC 1108 assembly code. Along with P and V is the code for bounded buffers, with the operations "PUT" and "GET". Bounded buffers are what Go calls "channels". Note how simple they are if you have P and V. That code even works on multiprocessors. There's one semaphore for "queue full" and one for "queue empty". PUT does a P on "queue full", puts on an item, and does a V on "queue empty". GET does a P on "queue empty", takes off an item, and does a V on "queue full". It's very simple. That's the real use case for P and V. Linus' note indicates that in 1999 he didn't know this.
(I didn't write those primitives, but I've used that code, and once ported it to a Pascal compiler I adapted to handle concurrency.)
This stuff was all well understood four decades ago. Much of it was forgotten outside the mainframe world, because threads and multiprocessors didn't make it to microprocessors for several more decades. UNIX, for a long time, had very primitive synchronization primitives. Early UNIX didn't have threads, and even after it got threads, it took years before the locking primitives settled down. The DOS/Windows world didn't get them until Windows NT, circa 1993.
It's been amusing to me to see bounded buffers resurface in Go. They're quite useful, and I've been using them in concurrent programs for many years.
As an aside, this paper (it's actually the transcription of a lecture) has some great metaphors that explain problems with concurrence and issues with synchronisation. At the risk of losing much of the nuances, he essentially illustrates the synchronisation using the example of a teacher who needs to find a pupil in a class. When pupils are free to choose a seat, she needs to scan all seats when she is looking for a particular pupil; but when at the same time pupils are free to change seats as she's scanning, there is no guarantee that she will ever find the pupil she's looking for as he might run from the back of the class to the front as soon as she's done scanning the front.
This makes more sense to me.
These documents are available from the Dijkstra archive: http://www.cs.utexas.edu/users/EWD/welcome.html
Here's an important distinction to make: this stuff was well understood in theory, but the practice is a bit different.
Semaphores are a neat theoretical concept but not a very good practical parallel programming paradigm. Semaphores are easy to reason about when writing proofs by induction that a parallel programming algorithm is working correctly, which is why they are still at the core of parallel programming education.
But when writing practical multithreaded programs, mutexes and condition variables are a lot more practical. Typically each mutex is coupled with one or more condition variables to wait/signal for conditions such as "queue not full" and "queue not empty". Incrementing and decrementing numeric counters is a very clumsy way to maintain a state of any kind. Implementing a semaphore requires grabbing a spinlock and doing this several times is unnecessary when you could just grab one mutex, check for the appropriate condition(s) and then wait/signal on the correct condition.
It is rather unfortunate that parallel programming is still primarily being taught in the theoretical manner (at least I was) using primarily semaphores, leaving too little emphasis on the practical implementation. It is important to understand the theory and know how to do the proofs but it is equally important to apply this into practice.
Every time I see someone "implement" a semaphore using a pthread mutex and condition variable, I cry a little. I've seen this several times in production code.
> It's very simple. That's the real use case for P and V. Linus' note indicates that in 1999 he didn't know this.
I'm pretty sure Linus was joking and he did understand what semaphores are used for. Every computer science curriculum has a course on parallel programming with bounded buffer producer consumer/problems, readers/writers problems and other "toy problems" solved using semaphores, followed by proof by induction that the solution is correct. And Linus did, eventually, finish a degree on computer science.
And you don't necessarily need a mutex or to actually put the thread to sleep. Semaphores are also relevant when speaking of asynchronous stuff (e.g. Futures), in which case you can easily do CAS operations on an atomic reference holding an immutable queue of promises. Slightly inefficient under high contention, but non-blocking and gets the job done.
Take the "rate limiting" example you mention (also one of Linus' examples in the OP). You initialize a semaphore to `max_concurrent_connections` and call `semaphore_down()` when you enter the connection handling sequence and `semaphore_up()` when you're done. Now this works fine and is an idiomatic example of using semaphores.
However, in the real world, this kind of situation rarely happens in isolation. What happens if you need to terminate the application for whatever reason, and do so cleanly? If you're under contention, you might have a dozen threads waiting for the semaphore go up and your only option is to kill them. Or implement some logic for this case (using another semaphore) to make sure the application hasn't been terminated while we were waiting for the rate limiting semaphore.
You can implement this cleanly using mutexes and conditions, by creating a "killable semaphore" synchronization primitive. While this is similar to a semaphore as an idea, it's very difficult to implement it if semaphores are the only primitive you have. Additionally, you probably want some kind of timeout if the queue is full.
So in practice you need something like:
while(true) {
socket = accept();
int status = rate_limiting_enter(my_rate_limiter);
// NOTE: someone else may call rate_limiting_terminate()
if(status == OK) {
service(socket);
rate_limiting_leave(my_rate_limiter);
} else if(status == TIMEOUT) {
send_busy(socket);
} else if(status == KILLED) {
send_terminate(socket);
break;
}
close(socket); // this must be called or resources leak
}
Now, while this is theoretically very similar to a semaphore, it has other real world priorities (like timeout and termination) which are very difficult to implement using Dijkstra -style semaphores with only P() and V() operations (and you definitely need more than one semaphore).This has been the case in almost every practical multithreaded programming scenario I've had. The solution could be thought of using semaphores (and I frequently do) but in practice, there's always some real world conditions (timing, contention, errors) that must be met.
It is very trivial to implement semaphore-like synchronization primitives using mutexes and conditions but not vice versa.
Semaphores are very good for textbook examples and a mental model but not so much in practical software.
Semaphores can be implemented in a way that doesn't require a spinlock in the fast path. Still not as fast as you can make a mutex, but a lot better than the pseudocode given in many classes (which is almost always wrong, too.)
(UNIVAC assemblers were very powerful. Arbitrary computation could be done at assembly time. If you needed some precomputed table, that was the way to do it.)
(FWIW, I think it's fairly normal for macro assemblers to be Turing-complete, although some of them carry it off more gracefully than others.)
Systems using these operations are in general not "composable". In other words, it is usually not possible to compose two software systems using semaphores and/or mutexes, without rewriting these systems somehow.
Alternatives exist. For example: message passing, and STM (software transactional memory). Anybody know of other alternatives?
Message passing can be asynchronous, but on some level, the system might have to synchronize certain operations. If you implement a financial system, you'll certainly have to synchronize stuff even if you're using asychronous message passing to implement it -- you will simply implement synchronicity on the top of an asychronous infrastructure.
And when operations start to depend on each other, then you _have_ to think about potential deadlocks, race conditions, etc.
Basically there isn't anything that solves this for you. STM is somewhat different as the danger is not deadlocks but starvation, etc.
There's nothing that "solves" the problem, but there are "things that will summon forth C'thulu" and "things that are merely difficult".
It should be noted that spinlocks, mutexes and conditions (and semaphores) are building blocks that are necessary to implement message passing, software transactional memory and other non-trivial parallel programming constructs. (at least until we have practical hardware transactional memory).
Spinlocks, mutexes and conditions are a "necessary evil", not "considered harmful".
Morealso STM doesn't solve the transactional problem that you face with using locks (mutex). Overall STM is just a fancy thing to have but hardly solves the big problem of transaction boundaries.
Message passing is easier to reason about due to global ordering but then you need some FIFO queues that are built upon some kind of mutex or spin lock... or Lamport based one (using for single producer-> single consumer one)... or some variant of Michael & Scott queue, etc.
In the end underneath you have to do the metal, so they cannot be 'considered harmful'.
Quotes like this are why I always read what Linus has to say, regardless of whether the subject is relevant to my life in the slightest.
Edit: Yes people, those Dutch words exist! I get it! I'm sure Linus was well aware of that when he made this remark. However, the point Linus was making (in a humorous way) was that like most computer scientists / mathematicians, Dijkstra was overly fond of obscure, single-letter names, which nobody ever intuitively understands. Whereas the names "up" and "down" (see the rest of Linus' quote) are far more intuitive. Personally, I would argue that "hold" and "release" convey the intent in a clearer, more abstract way.
Dijkstra was a computer scientist in times where being a computer scientist meant you were basically a mathematician with a specialty. Semaphores were first introduced by him in one of his early EWDs (EWD35, http://www.cs.utexas.edu/users/EWD/ewd00xx/EWD35.PDF). At the time of EWD35, his EWDs were non-official musings, written in Dutch, intended to be shared amongst interested colleagues and such. It's not like he was writing a scientific paper.
I don't think Torvalds really meant anything much by it. He's just trying to be funny.
If he was making this point, I find it ironic, considering that the purpose of the post is to explain the distinction between two obscure, poorly-named technical words, which nobody ever intuitively understands.
(ˈsɛməˌfɔː) n 1. (Telecommunications) an apparatus for conveying information by means of visual signals, as with movable arms or railway signals, flags, etc 2. (Telecommunications) a system of signalling by holding a flag in each hand and moving the arms to designated positions to denote each letter of the alphabet vb 3. (Telecommunications) to signal (information) by means of semaphore
which definition fits your understanding that you 'wait'? It's not a good name.
If you use a word too common, it's too easy to confuse the definition of that word with the definition of its use in a different context. You must not understand the pain of reading two mathematical books and trying, with the utmost sincerity, to figure out whether the authors are actually using the words the same (such as set, relation, abstraction, object, even things like function). There's the distinct definition, and there is the contextual use, which can theoretically differ for everyone depending on the origin path of native language. You can never know if someone is altering the definition or discovering / describing something new, and they are using the wrong word. Discovering the perfect word for the concept you construct in code or math is an art.
I personally have made remarks that were WAY more potentially offensive than that, verbally, with friends. But, accusing Dijkstra of being a drug user, on the Linux kernel mailing list, from a @transmeta address?
That's grounds for termination in many companies, even if you don't get lawyers involved. I think he's only able to get away with it because he's Linus.
Maybe you can edit the title and add a little [199] :-)
Linus spends much of his time being polite and helpful on many mailing lists, but it's his outbursts that make headlines, and convince the easily convincable that he's "rude".
No, it's not. Quit taking blogs at face value.
Linus is the BDFL of the Linux kernel, and he obviously needs to think about the big picture. And yet in these comments he gets into nitty-gritty assembly language.
I love it when a big picture guy also sweats the details.
If I am in a multiprocessor design, where each processor runs completely independent from each other and there is no central organizational unit like a central OS, like in many embedded designs, there is no such thing as a spinlock. A semaphore is also not used for sending processes to sleep.
Linus explanation makes sense, speaking only about a single OS, which may is comprised of multiple processors. But makes no sense at all for real multi-processor designs. I don't blame him for his narrow view, more his professors that he never experienced real embedded design.
I have worked in the past with multi-processors designs, where one processor was using one OS, like OS9, and the other processor had no OS at all running. Both processors where exchanging data via a dual ported RAM. So basically both processes where competing for the same resource. But even than, using a semaphore does not prevent race-conditions. Even then it is very tricky to use them. Because dual ported RAM allowed real concurrent access to the same resource.
In summary, the semaphore definition is the more broad definition where 2 (or more) processes are competing for a single resource. The naming convention within Linux is more specific for this requirements. The "invented" spinlock is just a renamed version for a fast semaphore, AFAIK. Even a mutex is just a special case of a semaphore.
4-thread x64:
mutex (480s): http://benchmarksgame.alioth.debian.org/u64q/program.php?tes...
sem_wait (476s): http://benchmarksgame.alioth.debian.org/u64q/program.php?tes...
cond_wait (271s - runs single-threaded?) http://benchmarksgame.alioth.debian.org/u64q/program.php?tes...
1-thread x86:
mutex (136s): http://benchmarksgame.alioth.debian.org/u32/program.php?test...
sem_wait (131s): http://benchmarksgame.alioth.debian.org/u32/program.php?test...
cond_wait (156s): http://benchmarksgame.alioth.debian.org/u32/program.php?test...
For example, the per-VM memory management semaphore could very usefully
be a blocking read-write lock, but without heavy thread contention a
mutex semaphore is basically equivalent.
has actually come to pass: the mm_struct is now protected by struct rw_semaphore mmap_sem."" They originally had operations called "P()" and "V()", but nobody ever remembers whether P() was down() or up(), so nobody uses those names any more. Dijkstra was probably a bit heavy on drugs or something (I think the official explanation is that P and V are the first letters in some Dutch words, but I personally find the drug overdose story much more believable). ""
Semaphores are not very good in practical programming but they're still valuable as a mental model and reasoning about algorithms.
It is a lot easier to prove by induction that an algorithm implemented with semaphores works than it is to deal with mutexes and conditions in a formal proof.
So semaphores are very useful in theoretical work, mutexes and conditions are more useful in practice.
The Little Book of Semaphores by Allen Downey
We were just told about mutexes, but I never knew that it stood for Mutual Exclusion. (I did correctly intuit that a mutex was simply a specific use case of semaphore though so I'm happy and managed to pass the course in the end :D)
Random question, does anyone know what some more active newsgroups lists are today or has it all slowed down?
And please, don't come up with async/await, callback/continuation, node.js' async stuff. They are not a replacement for mutual exclusion, etc.