线程加锁两次-死锁问题实验

    今天遇到了这个问题,晚上回来写个例子试试,试试证明还是会死锁的。

一个不同线程分别加锁的例子,这种情况是不会死锁的。

#include #include pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int count = 0; void * thread_func_one(void *arg) { int i; for(i=0;i<10;i++){ pthread_mutex_lock( &mutex1); count++; sleep(1); pthread_mutex_unlock(&mutex1); printf("thread one count value is %d/n",count); } return NULL; } void * thread_func_two(void *arg) { int i; for(i=0;i<10;i++){ pthread_mutex_lock( &mutex1); //pthread_mutex_lock( &mutex1); count++; sleep(1); //pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex1); printf("thread two count value is %d/n",count); } return NULL; } int main ( int argc, char **argv) { pthread_t thread_one, thread_two; if( 0!=pthread_create( &thread_one, NULL, thread_func_one,NULL)){ printf("pthread create failed!/n"); return -1; } if( 0!=pthread_create( &thread_one, NULL, thread_func_two,NULL)){ printf("pthread create failed!/n"); return -1; } pthread_join(thread_one, NULL); pthread_join(thread_two,NULL); return 0; }


以上这种情况,是不会影响的,共享全局变量都是在不同的线程加锁,线程2会等线程1的锁释放掉才执行

 

 

另外一种是在一个线程里加锁两次,这种情况,必挂,代码如下:

#include #include pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int count = 0; void * thread_func_one(void *arg) { int i; for(i=0;i<10;i++){ pthread_mutex_lock( &mutex1); pthread_mutex_lock( &mutex1);//锁两次 count++; sleep(1); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex1); printf("thread one count value is %d/n",count); } return NULL; } void * thread_func_two(void *arg) { int i; for(i=0;i<10;i++){ pthread_mutex_lock( &mutex1); //pthread_mutex_lock( &mutex1); count++; sleep(1); //pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex1); printf("thread two count value is %d/n",count); } return NULL; } int main ( int argc, char **argv) { pthread_t thread_one, thread_two; if( 0!=pthread_create( &thread_one, NULL, thread_func_one,NULL)){ printf("pthread create failed!/n"); return -1; } if( 0!=pthread_create( &thread_one, NULL, thread_func_two,NULL)){ printf("pthread create failed!/n"); return -1; } pthread_join(thread_one, NULL); pthread_join(thread_two,NULL); return 0; }

 

编译出来的程序,执行不下去的!~

 

今天遇到了这个问题,大家注意一下吧,同一个线程加锁两次必挂,不同的线程加锁,会等待第一把锁释放掉!

你可能感兴趣的:(thread,null,join)