问题 |
答案 |
|
开始学习
|
|
Smallest unit of execution scheduled by the OS. Threads of one process share address space (code, heap, globals, open files); each has own stack, registers, PC and TLS. Cheaper to create/switch than processes, but shared data needs synchronization.
|
|
|
|
开始学习
|
|
create/spawn (entry function + arg), join (wait for end, get result), detach (runs independently, auto-cleanup), exit/cancel, self/id, yield, sleep. E.g. pthread_create/join/detach, std: thread, std: jthread. A thread must be joined or detached.
|
|
|
|
开始学习
|
|
Plain (non-recursive): relock by owner = deadlock/UB. Recursive: owner may lock N times, unlock N times. Timed: try_lock_for/until. Shared (RW): many readers or one writer. Spinlock: busy-waits, for very short sections. Error-checking: reports misuse.
|
|
|
Mutex: general use cases and API 开始学习
|
|
Use: protect critical sections/shared data from races, keep invariants, pair with condition variables. API: lock (blocks), try_lock (no block), unlock; only owner unlocks. Prefer RAII: lock_guard, unique_lock, scoped_lock (multi-lock w/o deadlock).
|
|
|
General multithreading concepts 开始学习
|
|
Race condition: result depends on timing. Data race: unsynchronized access, ≥1 write. Critical section, atomicity. Deadlock (cyclic wait), livelock, starvation. Thread safety, reentrancy. Tools: mutex, semaphore, condvar, atomics. Concurrency≠parallelism.
|
|
|
Preemptive thread scheduling 开始学习
|
|
OS forcibly interrupts a running thread (timer tick ends its time slice, or higher-priority thread becomes ready), saves context and switches. No cooperation needed, so a switch may happen between any two instructions; hence races. Vs cooperative: yield.
|
|
|
|
开始学习
|
|
Number hinting scheduler who runs first; higher preempts lower. Static (real-time: FIFO/RR) or dynamic (OS boosts/decays). Risks: starvation of low prio; priority inversion (high waits on lock held by low) - fixed by priority inheritance/ceiling.
|
|
|
|
开始学习
|
|
New (created) → Ready/Runnable (waits for CPU) → Running (on a core) → Blocked/Waiting (I/O, lock, sleep, join, condvar; back to Ready when event occurs) → Terminated. Running → Ready on preemption or yield. Scheduler dispatches Ready → Running.
|
|
|
Factors affecting performance of multithreaded applications 开始学习
|
|
Serial fraction (Amdahl), lock contention, context-switch & thread creation cost, oversubscription (threads > cores), false sharing & cache misses, memory bandwidth, NUMA, sync/atomic overhead, load imbalance, task granularity, I/O waits.
|
|
|
|
开始学习
|
|
Max speedup with N processors: S(N) = 1 / ((1-p) + p/N), p = parallelizable fraction. As N→∞, S → 1/(1-p): serial part limits gain. E.g. p=0.9 → max 10x; N=8 gives ~4.7x. Assumes fixed problem size (cf. Gustafson's law).
|
|
|