Deadlocks, Explained | Introduction to Operating Systems

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 3.5 Free with a free account

Deadlocks

Introduction to Operating Systems · Chapter 3: Concurrency, Synchronization, and Deadlock PreventionSection 3.5 · lesson 22 of 838 min · free with a free account

← Mutual ExclusionNext lesson: Transactions →

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

How circular waiting freezes threads and how systems stop it.

  • Define a deadlock and draw one as a resource-allocation graph
  • Name the four Coffman conditions and explain how breaking one prevents deadlock
  • Apply the banker's algorithm safety test to find a safe sequence
  • Compare deadlock prevention, avoidance, and detection with recovery

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,185 words). Read along, or search it.

Opening Scene

Two Cars on a One-Lane Bridge

Two cars meet on a one-lane bridge, nose to nose. Each driver waits for the other to back up. Neither will, and neither can, because the car behind each one is stuck too. Nothing is broken, yet nothing will ever move again. Programs can do exactly this to each other. And when they do, no error appears. They simply stop. So how does it happen, and how do systems prevent it?

Definition

Threads Waiting on Each Other

A deadlock is when a set of threads are all waiting, and each one waits for something another one of them holds. So none of them can ever go on. Take two bakers. Ana holds the oven, and wants the mixer. Ben holds the mixer, and wants the oven. Each one will let go only after finishing, and neither can finish without the other's tool.

Resource-Allocation Graph

Arrows That Close a Loop

A resource-allocation graph draws this. Circles are threads or processes, and squares are resources. An arrow from a resource to a thread means the thread holds it. The oven points to Ana, and the mixer points to Ben. An arrow from a thread to a resource means the thread is waiting for it. Ana points to the mixer, and Ben points to the oven. Follow the arrows, and you go around a closed loop. When every resource has a single unit, a loop like this is a deadlock.

Four Conditions

Coffman's Conditions for Deadlock

In 1971, Coffman, Elphick and Shoshani described four conditions that must all be true for a deadlock to happen. Break any one of them, and deadlock can't happen. Mutual exclusion: a resource can be held by only one at a time. One oven, one baker in it. Hold and wait: a thread keeps what it holds while it asks for more. Ana keeps the oven while asking for the mixer. No preemption: nobody can take a resource away. Only the holder gives it back. And circular wait: a ring of threads, each waiting for the next one's resource. Ana waits for Ben, and Ben waits for Ana.

Simple Cure

A Fixed Lock Order

The easiest cure is to give every lock a fixed order, and make everyone follow it. If both bakers take the oven first and the mixer second, nobody can ever hold the mixer while waiting for the oven. Whoever gets the oven first also gets the mixer, finishes, and lets go of both. The circle can't form, so this breaks circular wait.

Quick Check

A Waiting Line Is Not a Loop

Quick check. Three jobs. Job T1 holds resource A, and waits for resource B. Job T2 holds B, and waits for C. Job T3 holds C, and isn't waiting for anything. It's still running. Is this a deadlock? Pause, and decide. No. T3 can finish, and when it does, it gives C back. Then T2 gets C, finishes, and frees B. Then T1 gets B, and finishes too. Waiting in a line isn't deadlock. Only a closed loop is, and these arrows never come back to where they started.

Prevention

Make One Condition Impossible

Prevention means designing the system so that at least one condition can never be true. Mutual exclusion: share what can be shared, like a read-only file. But printers and locks can't be shared. Hold and wait: ask for everything at the start, or let go before asking for more. Resources may then sit idle. No preemption: let the system take a resource back. That works for the CPU or memory pages, but not for a half-written file. Circular wait: number the resources, and always ask in rising order. That's the fixed lock order from before.

Avoidance

Safe States and the Banker's Algorithm

Avoidance is gentler. It lets all four conditions exist, but it checks every request first. It says yes only if the system stays in a safe state: one where some order exists in which every process can still finish. The best-known method is the banker's algorithm, again by Dijkstra. It's named for a banker who lends only when, in the end, every customer can still be paid. Each process declares up front the most it may ever need: its Max. The system tracks what each one holds, and works out its Need: Max minus what it holds.

Worked Example

Sam's Resource Table

Sam, who runs a small online bakery, has three kinds of resource, A, B and C: ten, five and seven units in all. And five jobs, P0 to P4. For each job, the table shows what it holds now, and what it still needs. P1's Max is three, two, two, and it holds two, zero, zero. So it needs one, two, two. The holdings add up to seven, two and five. So what's free is three, three and two.

Safety Test

Finding a Safe Sequence

The safety test repeats one step. Find a job whose need fits inside the free pool. Pretend it runs to the end and gives back everything it holds, and add that to the pool. P1 needs one, two, two, which fits in three, three, two. It finishes, and the pool grows to five, three, two. P3 fits next, and the pool becomes seven, four, three. Then P0, then P2, then P4. Every job got its turn. So the state is safe, and that order is a safe sequence.

Quick Check

Why P4's Request Must Wait

Quick check, on the same table. P4 asks for three, three, zero more. That fits inside the free pool of three, three, two. Should the system grant it right away? Pause, and decide. Deny it, for now. After the grant, the free pool would hold just zero, zero, two. P4 would still need one, zero, one. P3 needs a B, and everyone else needs more. No need fits, so no safe sequence exists. Shortage isn't the reason: three, three, zero fits in what's free today. Avoidance judges a request not by whether it fits now, but by whether everyone can still reach the end. So P4 waits. And unsafe doesn't mean deadlocked. It only means the system can no longer promise that everyone will finish.

Detection and Recovery

Cycles in a Wait-for Graph

Many systems use neither prevention nor avoidance, because declaring a Max in advance is rarely possible. They let deadlocks happen, and look for them. Detection draws a wait-for graph. An arrow from one process to another means: I'm waiting for something you hold. A cycle in that graph means a deadlock. The check runs every so often, or when the system looks suspiciously idle. To recover, the system can end one of the processes in the cycle, or all of them. Or it can take a resource away, and roll a process back to an earlier point.

Real Case

The Order and Refund Threads Freeze

Sam's shop met this too. One busy Friday, the order thread and the refund thread froze together. Nothing crashed, and nothing printed. Ivy, who looks after the computers at a school, checked which thread held which lock, and drew two arrows on paper: a loop. She changed the code so both threads take the order lock first. The freeze never came back.

Key Takeaways

Loops, Conditions and Three Strategies

To recap. A deadlock is a closed loop of threads, each waiting for what the next one holds. It needs four conditions at once, so prevention breaks one, like a fixed lock order. Avoidance, like the banker's algorithm, grants a request only if the state stays safe. And detection looks for cycles, then ends a process or rolls one back.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Deadlocks

What are the four necessary conditions for deadlock?
Deadlock requires four conditions at the same time: mutual exclusion, hold and wait, no preemption, and circular wait. Coffman, Elphick and Shoshani described them in 1971. Mutual exclusion means a resource has one holder at a time. Hold and wait means a thread keeps its resources while requesting more. No preemption means only the holder can release a resource. Circular wait is a ring of threads, each waiting for the next.
How does a fixed lock ordering prevent deadlock?
A fixed lock order prevents deadlock by making circular wait impossible. Every thread acquires locks in the same agreed sequence, for example the oven lock before the mixer lock. No thread can then hold a later lock while waiting for an earlier one, so a closed ring of waiting threads cannot form. It is one of the simplest and most practical cures for deadlocks in real code.
What is a safe state in the banker's algorithm?
A safe state is one in which some order exists that lets every process obtain its remaining need and finish. The banker's algorithm, devised by Edsger Dijkstra, grants a request only if the system stays in a safe state afterward. Each process declares its maximum need in advance, and its Need equals Max minus what it currently holds. An unsafe state is not yet a deadlock, but completion can no longer be promised.
What is the difference between deadlock prevention, avoidance and detection?
Prevention designs the system so that at least one of the four deadlock conditions can never hold. Avoidance allows all four conditions but checks every request, granting it only if the system stays in a safe state. Detection lets deadlocks happen, then periodically searches a wait-for graph for cycles. After detection, recovery ends one or more processes in the cycle, or takes a resource away and rolls a process back.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Operating Systems.

83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →