Mutex คือ lock ที่รับประกัน mutual exclusion — มีเพียง thread เดียวเท่านั้นที่ถือมันและเข้าสู่ critical section ที่ถูกป้องกันได้ในแต่ละครั้ง Semaphore ขยายแนวคิดนี้ให้อนุญาตผู้ถือพร้อมกันได้ถึง N ราย
Mutex คือ lock ที่รับประกัน mutual exclusion — มีเพียง thread เดียวเท่านั้นที่ถือมันและเข้าสู่ critical section ที่ถูกป้องกันได้ในแต่ละครั้ง Semaphore ขยายแนวคิดนี้ให้อนุญาตผู้ถือพร้อมกันได้ถึง N ราย
acquire() ลดค่า (บล็อกเมื่อถึง 0), release() เพิ่มค่า Mutex ก็คือ semaphore ที่ N=1 แต่มี 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 เพื่อให้ปล่อยอัตโนมัติแม้เกิด exceptionสิ่งเหล่านี้เป็นเครื่องมือพื้นฐานสำหรับปกป้อง state ที่แชร์ Mutex ทำให้การเข้าถึงเป็นอนุกรมเพื่อป้องกัน race; semaphore จำกัดปริมาณของ resource pool (connection, permit, rate limit) การเลือก primitive ที่ถูกต้องและรักษา critical section ให้สั้นคือความต่างระหว่าง ถูกต้องและเร็ว กับ ถูกต้องแต่ช้า
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค