FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Operating Systems

CSE

Progress0 / 6 lessons
  1. 1. What an OS actually does, and what a system call is
  2. 2. Processes vs threads, with a fork() example
  3. 3. CPU scheduling with worked FCFS, SJF and Round Robin numbers
  4. 4. Deadlock: the four conditions and how to break them
  5. 5. Memory: paging, virtual memory and page faults
  6. 6. File systems and how a file is really stored

Courses › Operating Systems

Deadlock: the four conditions and how to break them

A C program that deadlocks on purpose, the four necessary conditions, and the practical fix.

12 min read · Lesson 4 of 6 · Pro

A deadlock you can run

C
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;

void *worker1(void *arg) {
    (void)arg;
    pthread_mutex_lock(&A);
    printf("worker1 holds A, wants B\n");
    sleep(1);
    pthread_mutex_lock(&B);
    printf("worker1 got both\n");
    pthread_mutex_unlock(&B);
    pthread_mutex_unlock(&A);
    return NULL;
}
The rest of this lesson is Pro

The free lessons of Operating Systems finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.