多线程共同使用一个锁引发的死锁问题

今天大神同事遇到一个问题,如下:

如果两个线程共用一个线程锁,在A线程里面申请两次这个锁,B线程里释放一次,那么程序会正常运行吗,还是会阻塞在某个地方?


场景1:时间片竞争,各线程对锁的操作先后顺序未知

[root@zxx ~/testcode]$./pthreadlock 
thread two count value is 1
unlock thread two count value is 1
thread one count value is 1
lock1 thread one count value is 2

测试结果如上所示:线程二先释放锁,线程1申请锁成功,但是由于一直没有释放,因此在第二次申请锁的地方等待


场景2:通过sleep让线程1先申请锁,线程二再释放

[root@zxx ~/testcode]$./pthreadlock 
thread one count value is 1
lock1 thread one count value is 2
thread two count value is 2
unlock thread two count value is 2
lock2 thread one count value is 3

可以看到线程1先上锁了,紧接着线程2释放锁,线程1又申请锁,奇怪的是代码并没有在此等待锁的再次释放,正常执行完退出了。


对于锁的使用有很多种,也可以通过设置线程锁的性质来避免一些意外情况。经过进一步沟通,项目中的使用方式是在A线程发送数据包,B线程收到数据包之后解锁,那么实际情况跟场景二类似。但是还是不太理解为什么这么使用线程锁,唉,菜鸟一只,慢慢学习吧

附:例程

#include   

#include   
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;  
int count = 0;  


void * thread_func_one(void *arg)  

printf("thread one count value is %d\n",count); 
        pthread_mutex_lock( &mutex1);  
        count++;
        printf("lock1 thread one count value is %d\n",count);
       
        pthread_mutex_lock( &mutex1);//锁两次  
        count++;
        printf("lock2 thread one count value is %d\n",count);
        return NULL;  
}  
void * thread_func_two(void *arg)  
{  
        count++;  
        //sleep(1);
        printf("thread two count value is %d\n",count);
        pthread_mutex_unlock(&mutex1);  
        printf("unlock 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_two, NULL, thread_func_two,NULL)){  
                printf("pthread create failed!\n");  
                return -1;  
        }  
        pthread_join(thread_one, NULL);  
        pthread_join(thread_two,NULL);  
        return 0;  
}  

你可能感兴趣的:(多线程共同使用一个锁引发的死锁问题)