Deadlocks – Oh No !

Following my previous post about mutexes
I’ll get to the code straight away.

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


pthread_mutex_t lock1,lock2;



void* func1(void* data)
{

	
	pthread_mutex_lock(&lock1);
	sleep(1);
	pthread_mutex_lock(&lock2);
	printf("Function One\n");
	pthread_mutex_unlock(&lock1);
	pthread_mutex_unlock(&lock2);

	
}

void* func2(void* data)
{

	
	pthread_mutex_lock(&lock2);
	sleep(1);
	pthread_mutex_lock(&lock1);
	printf("Function Two\n");
	pthread_mutex_unlock(&lock1);
	pthread_mutex_unlock(&lock2);

	
}

void main()
{
	pthread_t t1,t2;
	pthread_mutex_init(&lock1, NULL);
	pthread_mutex_init(&lock2, NULL);
	pthread_create(&t1,NULL,func1,NULL);
	pthread_create(&t2,NULL,func2,NULL);
	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
}

Output ??

Well there isn’t any output. The program runs forever without displaying anything. Here’s why : t1 locks lock1 and t2 locks lock2. After waiting for 1 second t1 tries to get lock2 and t2 tries to get lock1. But both lock1 and lock2 are never unlocked since none of the proceeds to unlock them.
One is waiting for the other and nothing ever happens. The Classic Problem of Circular wait, Alas ! It’s a DEADLOCK !!

OK ! So what now ?

Unlike Mutual Exclusion there is no utility to avoid deadlocks. The only way to avoid deadlocks is by being smart while programming. It’s entirely up to the programmer in most cases to avoid them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s