死锁:代码中有多把锁,由于互斥锁使用不当造成代码无法运行的状态(两个线程都需要拿锁,谁都不愿意解锁。卡住了,造成整个程序停滞不前)
实例:线程1拿不到锁2,线程2拿不到锁1,造成死锁
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
int g_data=0;
void *func1(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex2);
for(i=0;i<5;i++){
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int*)arg));
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex);
printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
printf("t2:param is %d\n",*((int*)arg));
pthread_mutex_unlock(&mutex);
}
int main()
{
int ret;
int param=100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_mutex_init(&mutex2,NULL);
ret=pthread_create(&t1,NULL,func1,(void*)¶m);
if(ret==0){
printf("main:create t1 success\n");
}
ret=pthread_create(&t2,NULL,func2,(void*)¶m);
if(ret==0){
printf("main:create t2 success\n");
}
printf("main %ld \n",(unsigned long)pthread_self());
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex2);
return 0;
}
编译运行结果:造成死锁,ctrl+c退出进程
main:create t1 success
main:create t2 success
main 139666438145792
^C
CLC@Embed_Learn:~/thread$ ./a.out
main:create t1 success
main:create t2 success
main 139839917381376
^C
CLC@Embed_Learn:~/thread$ ./a.out
main:create t1 success
main:create t2 success
main 139912974800640
^C
CLC@Embed_Learn:~/thread$
只有1把锁的情况下是不会造成死锁的
在这里func1拿着锁mutex,需要拿锁mutex2;func2拿着锁mutex2,需要拿锁mutex;从而造成了死锁。