mutex అనేది mutual exclusion ను హామీ ఇచ్చే ఒక lock — ఒక సమయంలో ఒకే thread దాన్ని పట్టుకుని రక్షిత critical section లోకి ప్రవేశించగలదు. semaphore దీన్ని N concurrent holders వరకు అనుమతించేలా సాధారణీకరిస్తుంది.
mutex అనేది mutual exclusion ను హామీ ఇచ్చే ఒక lock — ఒక సమయంలో ఒకే thread దాన్ని పట్టుకుని రక్షిత critical section లోకి ప్రవేశించగలదు. semaphore దీన్ని N concurrent holders వరకు అనుమతించేలా సాధారణీకరిస్తుంది.
acquire() తగ్గిస్తుంది (0 వద్ద block అవుతుంది), release() పెంచుతుంది. mutex అనేది ప్రాథమికంగా N=1 తో ఉన్న semaphore కానీ ownership semantics తో.lock = threading.Lock()
def transfer(a, b, amt):
with lock: # critical section — one thread at a time
a.balance -= amt
b.balance += amt
# Semaphore: cap concurrent DB connections at 10
sem = threading.Semaphore(10)
def query():
with sem: # up to 10 threads run this concurrently
db.execute(...)
with/RAII/defer ను ఉపయోగించండి.shared state ను రక్షించడానికి ఇవి రోజువారీ tools. Mutexes races ను నివారించడానికి access ను serialize చేస్తాయి; semaphores ఒక resource pool (connections, permits, rate limits) ను నియంత్రిస్తాయి. సరైన primitive ను ఎంచుకోవడం మరియు critical sections ను చిన్నగా ఉంచడం correct-and-fast మరియు correct-but-slow మధ్య తేడా.
జూనియర్ నుండి సీనియర్ వరకు వివరణాత్మక సమాధానాలతో IT ఇంటర్వ్యూ ప్రశ్నల లైబ్రరీ.
విరాళం