Threads, atomics aur shared state
Data races, atomic updates, mutex invariants, release/acquire publication aur thread lifetime par reason karein.
Is chapter mein8 sections
Do threads overlapping timelines par work karke shared information access kar sakte hain. Unhein rules chahiye ki access kaun aur kab karega. Data races, atomic operations, mutex protection aur data publish karne ki ordering alag samjhenge.
1. Data races conflicting unordered accesses ki baat hain
Data race mein different threads ki conflicting actions, at least one non-atomic aur required happens-before ordering absent hoti hai. Conflicting pair same memory location access karta hai aur at least one modify karta hai. Data race undefined behavior hai. Sirf concurrent reads race nahi; single CPU, short sleep ya volatile synchronization supply nahi karte.
Happens-before relation specified within-thread sequencing aur inter-thread synchronization combine karta hai. Yeh language relation hai, sirf wall-clock observation nahi. Thread creation, successful joining, mutex operations aur correctly paired atomics ordering establish kar sakte hain. Thread-local state har thread ka separate object deta hai, doosre shared objects automatically safe nahi.
2. Individual atomic operations whole transactions nahi
#include <assert.h>
#include <stdatomic.h>
int main(void)
{
atomic_int counter;
atomic_init(&counter, 0);
int first_read = atomic_load(&counter);
int second_read = atomic_load(&counter);
atomic_store(&counter, first_read + 1);
atomic_store(&counter, second_read + 1);
int result = atomic_load(&counter);
assert(result == 1);
return 0;
}
Single-threaded model two imagined updates ke steps deliberately interleave karta hai: dono zero read karke one store karte hain. Har access atomic aur final value one hai. Real load-plus-store update one indivisible increment nahi. Suitable atomic read-modify-write operation ya multi-step invariant ke liye mutex use karein.
#include <assert.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <threads.h>
#if defined(__STDC_NO_THREADS__) || defined(__STDC_NO_ATOMICS__)
#error "This example requires C threads and atomics"
#endif
static atomic_uint counter;
static int increment(void *unused)
{
(void)unused;
for (unsigned i = 0; i < 1000; ++i) {
atomic_fetch_add_explicit(&counter, 1U, memory_order_relaxed);
}
return 0;
}
int main(void)
{
atomic_init(&counter, 0U);
thrd_t worker;
if (thrd_create(&worker, increment, NULL) != thrd_success) return EXIT_FAILURE;
(void)increment(NULL);
int worker_result = 0;
if (thrd_join(worker, &worker_result) != thrd_success) _Exit(EXIT_FAILURE);
if (worker_result != 0) return EXIT_FAILURE;
unsigned total = atomic_load_explicit(&counter, memory_order_relaxed);
assert(total == 2000U);
return EXIT_SUCCESS;
}
Worker aur main each thousand times add karte hain. Atomic fetch-add updates preserve karta hai aur two thousand har standard unsigned int mein fit hai. Is isolated counter ke liye relaxed ordering sufficient: atomicity milti hai, unrelated data publish nahi hota. Successful join final check se pehle completion establish karta hai. Hosted examples yahan GCC -pthread se link hote hain; build flags platform conventions hain.
3. Mutex larger invariant protect kar sakta hai
Mutex mutually exclusive access deta hai jab participating accesses lock discipline follow karein. Next version non-atomic counter protect karta hai. Final read worker join ke baad hai jab koi thread counter modify nahi karta. Ek lock hold karna elsewhere undisciplined accesses protect nahi karta; multiple locks mein deadlock avoid karne ko consistent ordering chahiye.
Mutex counter padhein
#include <assert.h>
#include <stdlib.h>
#include <threads.h>
#if defined(__STDC_NO_THREADS__)
#error "This example requires C threads"
#endif
static mtx_t gate;
static unsigned counter;
static int increment(void *unused)
{
(void)unused;
for (unsigned i = 0; i < 1000; ++i) {
if (mtx_lock(&gate) != thrd_success) _Exit(EXIT_FAILURE);
++counter;
if (mtx_unlock(&gate) != thrd_success) _Exit(EXIT_FAILURE);
}
return 0;
}
int main(void)
{
if (mtx_init(&gate, mtx_plain) != thrd_success) return EXIT_FAILURE;
thrd_t worker;
if (thrd_create(&worker, increment, NULL) != thrd_success) {
mtx_destroy(&gate);
return EXIT_FAILURE;
}
(void)increment(NULL);
int worker_result = 0;
if (thrd_join(worker, &worker_result) != thrd_success) _Exit(EXIT_FAILURE);
mtx_destroy(&gate);
if (worker_result != 0) return EXIT_FAILURE;
assert(counter == 2000U);
return EXIT_SUCCESS;
}
Bounded examples creation aur synchronization results check karte hain. Join failure par completion uncertain hai, isliye guessed lifetime mein resources destroy/continue karne ke bajay unrecoverable path par _Exit use hota hai. Mutex lock/unlock failures ka same emergency policy hai. _Exit normal cleanup bypass karta hai; production interfaces ko explicit failure policy chahiye, always recoverable assume nahi.
4. Data publication ko matching ordering relation chahiye
Relevant atomic rule mein release store us acquire load se synchronize kar sakta hai jo uska value read kare. One-shot example mein payload release se pehle written hai; consumer acquire se true observe karke hi payload read karta hai. Later payload write nahi. Relaxed flag replacement publication relation provide nahi karega.
- Producer
- Payload write, phir ready release-store
- Consumer
- True acquire-load, phir payload read
Publication example padhein
#include <stdatomic.h>
#include <stdbool.h>
#include <stdlib.h>
#include <threads.h>
#if defined(__STDC_NO_THREADS__) || defined(__STDC_NO_ATOMICS__)
#error "This example requires C threads and atomics"
#endif
static int payload;
static atomic_bool ready;
static int consume(void *unused)
{
(void)unused;
while (!atomic_load_explicit(&ready, memory_order_acquire)) thrd_yield();
return payload == 42 ? 0 : 1;
}
int main(void)
{
atomic_init(&ready, false);
thrd_t worker;
if (thrd_create(&worker, consume, NULL) != thrd_success) return EXIT_FAILURE;
payload = 42;
atomic_store_explicit(&ready, true, memory_order_release);
int result = 1;
if (thrd_join(worker, &result) != thrd_success) _Exit(EXIT_FAILURE);
return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Polling loop small model hai, fairness guarantee ya production-waiting recommendation nahi. Thrd_yield scheduling hint hai; C particular completion time promise nahi karta. Real waiting policy ke liye condition variables ya documented waiting facilities usually better hain; predicate synchronization contract ke under check honi chahiye.
5. Availability, lock freedom aur correctness different hain
C17 aur C23 mein threads/atomics conditional rehte hain, corresponding __STDC_NO_THREADS__ aur __STDC_NO_ATOMICS__ macros ke saath. Target implementation check karein. Atomic type necessarily lock-free nahi: atomic_is_lock_free property query aur matching ATOMIC_*_LOCK_FREE macros implementation guarantees describe karte hain. Sequentially consistent defaults ordering simplify karte hain, par larger algorithm ki logic/lifetime automatically fix nahi.
Primary references aur aage ki reading
- WG14 N1570 — public C11 committee draft: 5.1.2.4, 6.10.8.3, 7.17, 7.22.4.5, 7.26. C17 baseline ke stable core rules ke liye; final ISO publication nahi.
- WG14 N3096 — public C23 working draft: 5.1.2.4, 6.10.9.3, 7.17, 7.28. C23 notes C17 example checks se separately source-reviewed hain.
Aage badhne se pehle
- Shared mutable state ko required access aur ordering rules chahiye.
- Atomic operations larger multi-step update ko automatically transaction nahi banate.
- Synchronization, resource lifetimes aur API support design se match hone chahiye.
In ideas ko alag rakhein
- volatile / Synchronization
- volatile access valid inter-thread communication ki atomic ya locking rules ka substitute nahi.
Flag publish karne par uske associated ordinary data ke liye ordering agreement kyun chahiye?
Optional: bolkar samjhein ya note rakhein. Tayyar hon toh aage badh sakte hain.Apni understanding check karein
Optional hai. Answers save ya send nahi hote; chapter kabhi lock nahi hota.
Har choice ki explanation padhein
- Haan, volatile thread lock hai.
volatile mutex nahi aur apne aap atomicity ya synchronization nahi deta.
- Nahi. Suitable synchronization ya atomic-access design phir bhi chahiye.
✓ Sahi reasoning. Conflicting unsynchronized non-atomic accesses data race bana sakte hain.
- Har access indivisible operation ban jaata hai.
volatile generally ordinary operations ko atomic operations nahi banata.
C17
Earlier edition ka quick reference
Existing section links aur saved passages ke liye retained. Connected ideas expanded lessons mein hain; exact corrections source review mein recorded hain.
C mein standardized threading comparatively late aayi, C11 standard ke saath:
<threads.h>threads spawn aur wait karne ke liyethrd_create/thrd_join, mutual exclusion ke liyemtx_tmutexes, aur threads ke beech signaling ke liye condition variables provide karta hai. Support optional hai — jis implementation mein yeh nahi hai woh__STDC_NO_THREADS__define karke isse indicate kar sakti hai — aur practically, kai platforms abhi bhi POSIX threads (pthreads) par hi rely karte hain, jo C11 ki native threading support se pehle ki hain aur zyada widely available bhi hain.<stdatomic.h>atomic types (jaiseatomic_int) aur operations provide karta hai jo guaranteed data races ke subject nahi hote, saath hi explicit memory-ordering controls bhi dete hain un programmers ke liye jinhe threads ke across operations kaise visible hote hain uspar fine-grained control chahiye. Threading ki tarah, atomic support bhi technically optional hai (__STDC_NO_ATOMICS__)._Thread_local(Section 15) har thread ko ek variable ka apna independent copy deta hai — jaise thread-localerrnojaisi per-thread state ke liye useful.
C11 ne memory model introduce kiya jo inter-thread ordering aur data races define karta hai. Data race mein different threads ke conflicting actions hote hain (kam se kam ek object modify karta hai), kam se kam ek non-atomic access hota hai aur required happens-before ordering nahi hoti; data race undefined behavior hai. Sirf concurrent reads data race nahi. Mutexes, correctly used atomics aur thread creation/join ordering required ordering establish kar sakte hain. Atomic object se poora multi-step algorithm automatically atomic nahi hota aur volatile synchronization ka replacement nahi.
Agla idea padhne ke liye tayyar?
Mark this chapter as read whenever you feel ready.