> Now I got a broader question, why CAS is hardware supported, but lock is not > (i.e., why it is not the other way around)? I used to work on some firmware, > and we have hardware mutex. Why this is not generally the case for general > purpose CPUs?
There's several issues at work here, I'll try to cover them, but this comes with a massive disclaimer I'm going to be radically oversimplifying here. Two factors at work here is the fact that modern CPUs have several layers of caches (L3, L2, and L1 in most modern multi core CPUs). Secondly, modern systems can have cores that share none or more of these caches. So this all has to be handled in some way. In addition, most systems only support loading memory in cache lines. IIRC, today most cache lines are 16KB. So when you read a single byte, the 16KB around that memory location is loaded as well. So, when you do a swap in a x86, it first tells all other cores in the system to flush their cache lines that correspond with the memory location the swap is about to happen on. This will cause these CPUs to lock if they attempt to read from that cache line. From there the core is free to update the cache line and write it out to memory, and then finally release it back to the other CPUs. If this all sounds expensive, it really is. Part of this too is that CPUs buffer reads/writes in queues, before a swap the pending reads/writes must be flushed. Frankly I'm amazed that CAS works as well as it does. So there's a odd side-effect here. Notice how it locks a whole cache line (16KB)? This means that if you allocated 4K atoms from the same cache line, swapping one would cause the others to lock during the CAS. You can probably imagine how bad this would all get if we were allowed to just randomly start and stop locks. So yeah, there it is, simplified (and probably partly wrong). Hope that helps ;-) Timothy -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en