100 likes | 248 Vues
Disable/Enable Interrupts. Disable_interrupts(); <<< critical section >>> Enable_interrupts();. Test-and-Set. TS (<mem loc>) { if (<memloc> == 0) { <mem loc> = 1; return 0; } else { return 1; }. Mutex: Spin Lock.
E N D
Disable/Enable Interrupts • Disable_interrupts(); • <<< critical section >>> • Enable_interrupts();
Test-and-Set • TS (<mem loc>) • { • if (<memloc> == 0) • { • <mem loc> = 1; • return 0; • } • else • { • return 1; • }
Mutex: Spin Lock • Acquire_mutex(<mutex>) /* Before entering critical section */ • { • while(TS(<mutex>)) • } • Release_mutex(<mutex>) /* After exiting critical section */ • { • <mutex> = 0; • }
Compare-and-Swap • CS (<mem loc>, <expected value>, <new value>) { • if (<memloc> == <expected value>)) • { • <mem loc> = <new value>; • return 0; • } • else • { • return 1; • } • /* Note: TS(x) == CS (x, 0, 1) -- TS is special case of CS */
Mutex: Spin Lock • Acquire_mutex(<mutex>) /* Before entering critical section */ • { • while (CS (<mutex>, 1, 0)) • ; • } • Release_mutex(<mutex>) /* After exiting critical section */ • { • <mutex> = 1; • }
Counting Semaphore - Semantics • /* proberen – test *. • P(sem) • { • while (sem <= 0) • ; • sem = sem - 1; • } • /* verhogen – to increment */ • V(sem) • { • sem = sem + 1; • }
Counting Semaphore (Non-blocking) Implementation • P (csem) { • while (1) { • Acquire_mutex (csem.mutex); • if (csem.value <= 0) { • Release_mutex (csem.mutex); • continue; • } • else { • csem.value = csem.value – 1; • Release_mutex (csem.mutex); • break; • } • } • }
Counting Semaphore (Non-blocking) Implementation • V (csem) • { • Acquire_mutex (csem.mutex); • csem.value = csem.value + 1; • Release_mutex (csem.mutex); • }
Counting Semaphore (Blocking) Implementation • P (csem) { • while (1) { • Acquire_mutex (csem.mutex); • if (csem.value <= 0) { • insert_queue (getpid(), csem.queue); • Release_mutex_and_block (csem.mutex); /* atomic: lost wake-up */ • } • else { • csem.value = csem.value – 1; • Release_mutex (csem.mutex); • break; • } • } • }
Counting Semaphore (Blocking) Implementation • V (csem) • { • Acquire_mutex (csem.mutex); • csem.value = csem.value + 1; • dequeue_and_wakeup (csem.queue) • Release_mutex (csem.mutex); • }