线程死锁演示

#include
#include
#include
#include 
#include
void *thread_function1(void *arg);
void *thread_function2(void *arg);
int students=0;
pthread_mutex_t work_mutex1;
pthread_mutex_t work_mutex2;
int main()
{
    int ret;
    void *thread_result;
    pthread_t a_thread;
    pthread_t b_thread;

    ret=pthread_mutex_init(&work_mutex1,NULL);
    if(0!=ret)
    {
        printf("error");
        exit(1);
    }

    ret=pthread_mutex_init(&work_mutex2,NULL);
    if(0!=ret)
    {
        printf("error");
        exit(1);
    }

    //创建线程
    ret=pthread_create(&a_thread,NULL,thread_function1,NULL);//线程创建成功返回0
    if(ret!=0)
    {
        printf("线程创建失败!");
        exit(0);
    }

    ret=pthread_create(&b_thread,NULL,thread_function2,NULL);//线程创建成功返回0
    if(ret!=0)
    {
        printf("线程创建失败!");
        exit(0);
    }

    //阻塞
    ret=pthread_join(a_thread,&thread_result);//阻塞成功返回0
    if(ret!=0)
    {
       printf("线程阻塞失败!"); 
       exit(0);
    }

    ret=pthread_join(b_thread,&thread_result);//阻塞成功返回0
    if(ret!=0)
    {
       printf("线程阻塞失败!"); 
       exit(0);
    }

    printf("\n");
    printf("%d\n",students);
    exit(0);
}

void *thread_function1(void *arg)
{
    int i=0;
    for(i=0;i<10000000;i++)
    {
        pthread_mutex_lock(&work_mutex1);
        pthread_mutex_lock(&work_mutex2);
        students++;
        printf("thread1  student  value %d\n",students);
        pthread_mutex_unlock(&work_mutex2);
        pthread_mutex_unlock(&work_mutex1);
    }  
}

void *thread_function2(void *arg)
{
    int i=0;
    for(i=0;i<10000000;i++)
    {
        pthread_mutex_lock(&work_mutex2);//两个线程上锁的顺序不一致导致的死锁
        pthread_mutex_lock(&work_mutex1);
        students++;
        printf("thread2  student  value %d\n",students);
        pthread_mutex_unlock(&work_mutex1);
        pthread_mutex_unlock(&work_mutex2);
    }  
}
//线程共享students变量

编译:
在这里插入图片描述
死锁:
线程死锁演示_第1张图片

你可能感兴趣的:(linux环境高级编程)