Deadlock Prevention and Banker's Algorithm in C

Posted by Anonymous and classified in Computers

Written on in English with a size of 2.93 KB

Dining Philosophers Deadlock Prevention

The following implementation addresses the Dining Philosophers problem using POSIX threads and semaphores. To prevent deadlock, the logic ensures that the last philosopher picks up the forks in a different order than the others.

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>

#define N 5

sem_t forkS[N];

void *philosopher(void *n)
{
    int id = *(int *)n;
    int left = id;
    int right = (id + 1) % N;

    while (1)
    {
        printf("P%d Thinking\n", id);

        fflush(stdout); // Force print immediately
        sleep(1);

        // Deadlock prevention: last philosopher picks right fork first
        if (id == N - 1) {
            sem_wait(&forkS[right]);
            printf("P%d picked up fork %d\n", id, right);
            sem_wait(&forkS[left]);
            printf("P%d picked up fork %d\n", id, left);
        } else {
            sem_wait(&forkS[left]);
            printf("P%d picked up fork %d\n", id, left);
            sem_wait(&forkS[right]);
            printf("P%d picked up fork %d\n", id, right);
        }
    }
}

Banker's Algorithm for Resource Allocation

The Banker's Algorithm is a resource allocation and deadlock avoidance strategy. It determines if a system is in a safe state by calculating a safe sequence of process execution.

#include <stdio.h>

int main()
{
    int n, m, i, j, k, c = 0, f[10] = {0}, safe[10];

    printf("Processes & Resources: ");
    scanf("%d%d", &n, &m);

    int a[10][10], max[10][10], need[10][10], av[10];

    printf("Allocation:\n");
    for(i = 0; i < n; i++)
        for(j = 0; j < m; j++)
            scanf("%d", &a[i][j]);

    printf("Max:\n");
    for(i = 0; i < n; i++)
        for(j = 0; j < m; j++)
            scanf("%d", &max[i][j]);

    printf("Available:\n");
    for(i = 0; i < m; i++)
        scanf("%d", &av[i]);

    for(i = 0; i < n; i++)
        for(j = 0; j < m; j++)
            need[i][j] = max[i][j] - a[i][j];

    while(c < n)
    {
        int found = 0;
        for(i = 0; i < n; i++)
        {
            if(!f[i])
            {
                for(j = 0; j < m; j++)
                    if(need[i][j] > av[j]) break;

                if(j == m)
                {
                    for(k = 0; k < m; k++)
                        av[k] += a[i][k];
                    safe[c++] = i;
                    f[i] = 1;
                    found = 1;
                }
            }
        }

        if(!found)
        {
            printf("Unsafe State");
            return 0;
        }
    }

    printf("Safe Sequence: ");
    for(i = 0; i < n; i++)
        printf("P%d ", safe[i]);

    return 0;
}

Related entries: