Multithreading
Table of Contents
In Linux you can create threads using the `clone` syscall [man clone 7]
In fact, `fork` (the syscall to create new process) and `clone` use the same mechanism underneath, in the kernel.
`clone` offers finer control to thread creation, and can be passed agruments to specify
- where to keep the thread stack
- what function to run
- whether to share file descriptors, memory (should the virtual memory table be duplicated or not)
- whether to use different IPC namespace, filesystem, cgroups
However, usually a higher level API (e.g. pthreads) provided by language or library is used instead of directly calling `clone`.
1. Pthreads
pthreads (aka POSIX Threads) is an API defined in a POSIX standard (POSIX.1c 1995). It is independent of programming languages and POSIX compliant operating system provide shared library to use pthreads.
- has ~100 functions (all with `pthread_` prefix)
- thread management
- condition variables
- mutexes
- synchronization (barriers)
- spinlocks
- semaphores are not included. It is available in different standard (POSIX.1b 1993).
In Linux, the modern pthreads implementation is call NPTL (Native POSIX Threads Library) [See man pthreads 7. Older implementation was called LinuxThreads]. NPTL uses `clone` syscall for thread creation, and `futex` syscall for synchronization primitives (mutexes, thread joining, and so on).
Is an N:1 POSIX Threads implemenation allowed?
- has ~100 functions (all with `pthread_` prefix)
Recommended study material for pthreads: https://hpc-tutorials.llnl.gov/posix/
2. Atomics
- Regarding locks and atomic instructions read the Rust Atomics and Locks section: https://marabos.nl/atomics/hardware.html