C: Deadlock

From AdonaiMedrado.Pro.Br
Jump to: navigation, search
#include <stdio.h>
#include <pthread.h>
 
int x;
pthread_mutex_t mutex_de_x, mutex_de_y;
 
void *minha_thread1(void *null)
{	
	pthread_mutex_lock(&mutex_de_x);
		printf("minha_thread1: Obtive acesso ao mutex X.\n");
		printf("minha_thread1: Aguardando 1 segundo...\n");
		sleep(1);
		printf("minha_thread1: Tentando mutex Y...\n");		
		pthread_mutex_lock(&mutex_de_y);
			printf("minha_thread1: Obtive acesso ao mutex Y.\n");
			printf("minha_thread1: Liberando mutex Y...\n");
		pthread_mutex_unlock(&mutex_de_y);
		printf("minha_thread1: Liberando mutex X...\n");
	pthread_mutex_unlock(&mutex_de_x);
 
	pthread_exit(NULL);
}
 
void *minha_thread2(void *null)
{	
	pthread_mutex_lock(&mutex_de_y);
		printf("minha_thread2: Obtive acesso ao mutex Y.\n");
		printf("minha_thread2: Aguardando 1 segundo...\n");
		sleep(1);
		printf("minha_thread2: Tentando mutex X...\n");		
		pthread_mutex_lock(&mutex_de_x);
			printf("minha_thread2: Obtive acesso ao mutex X.\n");
			printf("minha_thread2: Liberando mutex X...\n");
		pthread_mutex_unlock(&mutex_de_x);
		printf("minha_thread2: Liberando mutex Y...\n");
	pthread_mutex_unlock(&mutex_de_y);
 
 
	pthread_exit(NULL);
}
 
int main()
{
	int retorno_da_thread;
	pthread_t thread1, thread2;
	pthread_attr_t atributo_de_thread;
 
	pthread_attr_init(&atributo_de_thread);
	pthread_attr_setdetachstate(
		&atributo_de_thread, PTHREAD_CREATE_JOINABLE);
 
	pthread_mutex_init(&mutex_de_x,NULL);
	pthread_mutex_init(&mutex_de_y,NULL);
 
	if (pthread_create(&thread1,
		&atributo_de_thread,
		minha_thread1,NULL))
		printf("Erro ao criar a minha_thread1.\n");
 
	if (pthread_create(&thread2,
		&atributo_de_thread,minha_thread2,NULL))
		printf("Erro ao criar a minha_thread2.\n");
 
	if (pthread_join(thread1,(void **)&retorno_da_thread))
		printf("Erro no join de minha_thread1.\n");
	else
		printf("minha_thread1 joined.\n");
 
	if (pthread_join(thread2,(void **)&retorno_da_thread))
		printf("Erro no join de minha_thread2.\n");
	else
		printf("minha_thread2 joined.\n");
 
	pthread_mutex_destroy(&mutex_de_y);
	pthread_mutex_destroy(&mutex_de_x);
 
	pthread_attr_destroy(&atributo_de_thread);
 
	pthread_exit(NULL);
}