| How would you implement a mute... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
Rather block myself when I fail to get a spinlock and wait on a queue. Periodically, I will poll for the lock and repeat step 1.
Use a TSL to set the lock's state. Based on the value returned by the TSL decide whether to block itself or enter the critical region.
Q could be a simple FCFS or a thread priority based queue.
Pseudocode:
void mutex_lock_blocking(Mutex* mhandle, Thread* thandle)
{
spinlock_lock(mhandle->spinlock);
if(! is_Q_empty(mhandle->queue))
{
Q_push(thandle);
// Blocks thread. Scheduler can schedule threads with runnable == TRUE
thread->sched_runnable = FALSE;
spinlock_unlock(mhandle->spinlock);
// Calls the thread scheduler. Returns only when some other threas sets runnable = TRUE
// for the current thread.
scheduler_yield();
}
thread->sched_runnable = FALSE;
Q_push(thandle);
spinlock_unlock(mhandle->spinlock);return;
}void mutex_unlock(Mutex* mhandle, Thread* thandle)
{
spinlock_lock(mhandle->spinlock);
// Remove self from the Q
Q_remove(thandle);
// Mark next thread on Q. But do not pop it yet. next_runnable_thandle will resume
// resume execution just after returning from scheduler_yield() from mutex_lock_blocking
next_runnable_thandle = Q_get_next();
next_runnable_thandle->runnable = TRUE;
spinlock_unlock(mhandle->spinlock);
}
volatile int lock = 0;
void Critical() {
while (TestAndSet(&lock) == 1);
critical section //only one process can be in this section at a time
lock = 0 //release lock when finished with the critical section
}
i would make use of an atomic instruction like the test_and_set in x86 but instead of keeping the threads spinning and waiting..log them into a queue for both fairness and not wasting CPU cycles..