In: Computer Science
In a scenario where several threads are contending for a critical section there are 3 options for threads that fail to acquire the lock i) spin; ii) yield and iii) placed in a wait queue. Discuss the pros and cons of the 3 approaches.
1. Spin method
Pros
● suitable for use in interrupt context
● avoids indefinite sleep/wait of a thread as it keeps the thread active in a light loop
● very fast as no time is taken to put a thread in wait queue and again moving the thread to the ready queue
● low power consumption as moving task to wait queue and moving task to ready queue is a tiring process
Cons
● it must not be used in uniprocessor system as it can create deadlock
● spin method is not recursive
● spin lock need to be taken special care when it is used between interrupt handler and thread as it may cause deadlock
2. Yield
Yield temporarily pause the execution of current thread and let other threads to execute
Pros
● it lets the scheduler to choose any thread according to the priority of threads
● current process will continue execution if all the other process waiting in the queue are of lower priority
● if current thread is taking very long to execute, it gives chance for other threads waiting for long time hence reducing indefinite wait or starvation problem
Cons
●yield is a slow approach
● more context switches are there in yield as compared to spin
3. Place thread in a wait queue
In this synchronization approach, the scheduler puts the thread in sleep condition or move it to the wait queue(FIFO) . Semaphore is used for this approach
Pros
●it is a very simple approach
● most suitable for process context
● semaphore lets processes to be preempted
Cons
● increase CPU overhead as putting a task in wait queue and then invoking it again is long time consuming process.
● it is not flexible in terms of modifying the priority of threads as the thread put in wait queue first will move to ready state first
● slowest approch for synchronization