tags : Operating Systems, Concurrency
Each thread executes a thread function
Types
preemptive | not preemptive/cooperative | |
---|---|---|
parallel | native threads | programs on different computers? |
non-parallel | green threads | Coroutines |
Preemptive/Non Preemptive
- Having the ability the preempt means less chances of starvation.
Native Threads
OS threads basically
pthreads (posix threads)
- A
pthread
can be either be created as- A joinable thread (the default)
- A detached thread (cleaned up automatically when it terminates)
- Thread cancellation are of three types(
pthread_setcanceltype
)- sync
- async
- uncancellable (critical section)
Green Threads
- Language agnostic idea, implementations differ.
- User-level threads that are scheduled by a runtime/scheduler/library instead of the OS. They usually sit on top of OS threads.
- Green threads have threading semantics, that means that you need to deal with mutexes, atomics, etc.
- You should code as though the context can switch at any time
- Python’s greenlets. Golang has mix of greenthreads and os threads w goroutines etc. Ruby’s fibers are green threads. (See Python Concurrency)
Coroutines
- It can be used for concurrency, it’s cooperative multithreading when that happens.
- See Coroutines
Thread Safety
- Thread-Safety is just the ability to maintain an object’s invariants in a multi-threaded environment.
- Libraries/Methods can be: Thread safe, Conditionally safe, Not thread safe
When to use synchronization?
- Always avoid synchronization/shared-state if possible.
- If possible to keep things thread-local, do it, even if it costs some memory.
No Shared State
- Re-entrancy
- Subroutine is called reentrant if multiple invocations can safely run concurrently, i.e execution and then safely be called again/re-enter before its previous invocations complete execution.
- See Interrupts, Soft IRQs are re-enterant functions.
- Tread local storage
- It’s just storage specific to the running thread
- Many threads can have a variable called
a
;a
is local to each thread. One usage can be multiple threads accumulating information into a global variable with some kind of sync ofc.
- Immutable objects: What functional languages do
- Concurrency in Golang provides us with channels which allow goroutines to communicate w each other via message passing rather than shared state.
There is shared state
- Mutual Exclusion (Blocking)
- Locks and stuff. See Concurrency
- Atomic Operations (Non blocking)
- See Lockfree
Links
- OpenMP and pwrite()
- pthread debuging
- Rethinking the futex API {LWN.net}
- Debugging a futex crash
- Two Threads, One Core: How Simultaneous Multithreading Works Under the Hood | Lobsters
- You could have invented futexes | Hacker News 🌟
- mutexes in modern Linux kernels are actually implemented as futexes. ??
- Raw Linux Threads via System Calls
- Practical libc-free threading on Linux
- MutexProtected: A C++ Pattern for Easier Concurrency | Hacker News