标签:stdio.h types class sign std wait bsp printf logs
/* 头文件 */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pthread.h> #include <signal.h> pthread_mutex_t mutex_one,mutex_two; pthread_mutex_t mutex; pthread_cond_t cond; void *thread_routine_one(void *arg) { pthread_cond_wait(&cond,&mutex);//确保two线程先运行 printf("thread_routine_one: lock mutex_one!\n"); pthread_mutex_lock(&mutex_one); printf("thread_routine_one: lock mutex_two!\n"); pthread_mutex_lock(&mutex_two);//获取two锁,这个要等待two线程对two锁的释放 sleep(1); printf("thread_routine_one: unlock mutex_two!\n"); pthread_mutex_unlock(&mutex_two); printf("thread_routine_one: unlock mutex_one!\n"); pthread_mutex_unlock(&mutex_one); return NULL; } void *thread_routine_two(void *arg) { printf("thread_routine_two: lock mutex_two!\n"); pthread_mutex_lock(&mutex_two);//获取two锁 pthread_cond_signal(&cond);//让one线程运行 sleep(1);//休眠,让one可以先运行获取one锁 printf("thread_routine_two: lock mutex_one!\n"); pthread_mutex_lock(&mutex_one);//获取one锁,这个同样必须等待one线程多one锁的释放 /**这时出现死锁现象了,在two线程要等待one线程对one锁的释放,同时two锁没有释放 * 然而在one线程需要等待two线程对two锁的释放,然后才会对one锁的释放!出现相互等待的过程**/ printf("thread_routine_two: unlock mutex_one!\n"); pthread_mutex_unlock(&mutex_one); printf("thread_routine_two: unlock mutex_two!\n"); pthread_mutex_unlock(&mutex_two); return NULL; } void main() { pthread_t pthread_one,pthread_two; pthread_mutex_init(&mutex_one,NULL); pthread_mutex_init(&mutex_two,NULL); pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_create(&pthread_one,NULL,thread_routine_one,NULL); pthread_create(&pthread_two,NULL,thread_routine_two,NULL); while(1) sleep(1); }
线程程A已经拥有至少一个资源,此时又去申请其他资源,而该资源又正在被B线程使用,而同时B线程也在等待A线程的资源释放后才会释放自己的资源,便会造成死锁。此时请求进程阻塞,但对自己已经获得的资源保持不放,
标签:stdio.h types class sign std wait bsp printf logs
原文地址:http://www.cnblogs.com/mcy0808/p/7420955.html