In: Computer Science
In C programming: Using mutexes, semaphores, and spinlocks, you can sequence memory operations to prevent race conditions. It might make some sense to just chuck spinlocks out the window and use mutexes. Explain why mutexes would tend to relieve you of some of the problems inherent in spinlocks. Explain a situation in which those benefits might not be worth your time and you’d go with the spinlock anyway.
Mutex forces Mutual Exclusion at a time it allows only one process to hold the lock and enter the critical section. When a task attempts to acquire a mutex that is unavailable, the mutex places the task onto a wait queue and puts it to sleep. As the mutex allows the process to sleep, thus used in the user-space application.
The processor is then free to execute other code. When the mutex becomes available, one of the tasks from the wait queue is awakened so that it can acquire the mutex lock.A spinlock is a mutual exclusion device that can have only two values: “locked” and “unlocked”.
If the lock is available, the “locked” bit is set and the code continues into the critical section.
If instead, the locks been taken by somebody else, the code goes
into a tight loop where it repeatedly checks the lock until it
becomes available. This looping process is the “spin” part of a
spinlock.Spinlock continuously polling for spin waste the CPU time
and if the lock is held for more amount of time this will waste a
lot more CPU time.Spinlock is not preferable as when the lock is
not available and thread put to sleep, it would spin forever no
other thread would ever be able to obtain the CPU to release the
lock whereas by mutex if the thread was put to sleep, another
thread could have run at once, possibly unlocking the lock and then
allowing the first thread to continue processing once its wakeup.In
cases where the sleep time is large or you potentially need to
sleep while holding the lock, the mutex is a solution.Lastly mutex
can be held for a long duration of time. where as spinlock
can't.
When should we use Spinlock:-
When a thread tries to lock a mutex and it does not succeed,
because the mutex is already locked, it will go to sleep,
immediately allowing another thread to run. It will continue to
sleep until being woken up, which will be the case once the mutex
is being unlocked by whatever thread was holding the lock before.
When a thread tries to lock a spinlock and it does not succeed, it
will continuously re-try locking it, until it finally succeeds;
thus it will not allow another thread to take its place .In certain
places in kernel (interrupt context, other atomic contexts where
you cannot sleep) use spinlocks.