mutex એ એક lock છે જે mutual exclusion ની ખાતરી આપે છે — એક સમયે ફક્ત એક thread તેને પકડી શકે અને સુરક્ષિત critical section માં પ્રવેશી શકે. semaphore આને N સમાંતર holders સુધી સામાન્યીકૃત કરે છે.
mutex એ એક lock છે જે mutual exclusion ની ખાતરી આપે છે — એક સમયે ફક્ત એક thread તેને પકડી શકે અને સુરક્ષિત critical section માં પ્રવેશી શકે. semaphore આને N સમાંતર holders સુધી સામાન્યીકૃત કરે છે.
acquire() decrement કરે છે (0 પર block), release() increment કરે છે. 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 વાપરો જેથી exceptions પર પણ release આપોઆપ થાય.આ shared state ને સુરક્ષિત કરવાનાં રોજિંદાં સાધનો છે. Mutexes races અટકાવવા access ને serialize કરે છે; semaphores resource pool (connections, permits, rate limits) ને throttle કરે છે. યોગ્ય primitive પસંદ કરવું અને critical sections ટૂંકાં રાખવાં એ correct-and-fast અને correct-but-slow વચ્ચેનો ફરક છે.
વિગતવાર જવાબો સાથે IT ઇન્ટરવ્યૂ પ્રશ્નોની લાઇબ્રેરી — જુનિયરથી સિનિયર સુધી.
દાન કરો