1

To learn more about multithread programming I decided to implement my own version of some low-level memory object. I took a look at std::mutex because of this, and I was pretty intimidated and confused by its definition (compared to my style it's quite arcane, and I'm failing to track down simple things like function definitions). So, I decided to look at std::atomic instead, and the header is a whopping 1400 lines. Also seems like much of the code references "deeper down" machinery, if that makes sense. Uses the <bit> header file, and std::mutex is filled with included macro use.

Before I continue, is implementing any of this a practical goal without esoteric knowledge? Should I leave it to the compiler writers?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Anthony
  • 1,015
  • 8
  • 22
  • 1
    Both are easy to build educational versions of. The reason the compiler supplied versions are so large and esoteric is because they handle a ton of special cases and are also heavily optimized for that particular compiler. If you want to learn you wouldn't do any of that and your version would be simpler. – Adam Mar 30 '19 at 02:18
  • 1
    For atomics, look up "compare and swap" or "compare and set". That's all you need to implement atomic integers. Of course for arbitrary atomics you'd have to do lots of crazy stuff and your implementation might end up 1400 lines. – Adam Mar 30 '19 at 02:20
  • @Adam thanks for the reply. I read on 'test and set', which I assume is the same as 'compare and set'. Are there any resources you'd recommend? – Anthony Mar 30 '19 at 03:41
  • 1
    if you look at any standard headers you'll see a bunch of almost unreadable code, not only `atomic` [Why is the code in most STL implementations so convoluted?](https://stackoverflow.com/q/4180166/995714), https://developers.redhat.com/blog/2016/02/29/why-cstdlib-is-more-complicated-than-you-might-think/. You can check [Why STL implementation is so unreadable? How C++ could have been improved here?](https://stackoverflow.com/q/1460936/995714), [Is there a readable implementation of the STL?](https://stackoverflow.com/q/2127612/995714) – phuclv Mar 30 '19 at 06:19
  • @AnthonyMonterrosa If you want to know how mutex can work, check [this](https://softwareengineering.stackexchange.com/questions/340284/mutex-vs-semaphore-how-to-implement-them-not-in-terms-of-the-other/362533#362533) answer. –  Mar 30 '19 at 07:44
  • If you want an implementation from scratch, you will need to use some asm instructions to perform atomic read-modify-write which is required to implement mutexes. It depends on your architecture, but all processors have this kind of instructions (lock cmpxchg in x86, ll/sc on mips, etc). – Alain Merigot Mar 31 '19 at 21:00

0 Answers0