4 ms·
Seconded. It’s silly to learn threads “from the outside in” — thinking of them as an opaque abstraction and trying to understand the API they present. There’s n
by derefr 6y ago
Seconded. It’s silly to learn threads “from the outside in” — thinking of them as an opaque abstraction and trying to understand the API they present. There’s no coherent abstraction there; you’ll only learn to cargo-cult the API, without gaining an intuition for what threads “are” or when and where you’d want to use those APIs.
The key thing to know, is that threads aren’t a first-class kernel object. In OS kernels, there are only OS processes and memory regions.
To learn about threads, you should just learn about OS processes; and then learn that distinct OS processes can share memory regions between them, often via subprocess-spawn-time inheritance. Learn what fork(2) does on POSIX, and how it manages to be fast.
Starting with that intuition, it’s simple to then absorb what “threads” actually are: a usage pattern for spawning and managing OS processes that share memory; and a set of convenience APIs (that may be in-kernel, as in Windows; or purely in userland, as in Linux) for setting up this usage pattern. Everything these “threading” APIs can do, you can do yourself directly using the process-management and memory-mapping APIs. And those same calls are all that e.g. libpthread is doing.
- rusk 6y agoI just visualise it as different instruction pointers with their own stack and shared heap. But I’m coming from Java so that might be an oversimplification!
- formerly_proven 6y agoThis strikes me as rather focused on Linux kernel implementation details, since in Windows processes and threads are actually distinct concepts (as opposed to the Linux kernel, which really only knows about tasks), where every live process has n>1 threads and the address space of threads is afaik strictly defined through the process it is part of.
- djeiasbsbo 6y agoI know about unix/linux processes, ipc and the relevant system calls (exec*, fork, clone, ...) but where do I continue from there? Studying C, I haven't really come across threads other than trying out the things in `pthread.h`. Would you recommend just reading the source code of that header for a better understanding?