互斥锁和条件变量的结合使用

来源:互联网 发布:asp淘宝客源码 编辑:程序博客网 时间:2024/06/06 13:27
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <iostream>
using namespace std;
 
pthread_cond_t qready =  PTHREAD_COND_INITIALIZER;//初始构造条件变量
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;//初始构造锁
pthread_t tid1,tid2,tid3;
 
int x=10;
int y=20;
 
 
void*thrd_1(void*arg)
{
    pthread_mutex_lock(&qlock);
    
    printf("jiangxin before the pthread_cond_wait\n");
    
    pthread_cond_wait(&qready,&qlock); //个函数在qready条件没满足的时候会卡在这里,并且,会把传入的互斥锁解锁,为什么要解锁的,拟可以想想,
                                                     //如果不解锁的话,那外部就没有可以对x,y的修改权,应为其他两个线程想要修改这两个值的话都需要对qclock进行枷锁
    printf("jiangxin after the pthread_cond_wait\n");
    
    
    pthread_mutex_unlock(&qlock);
    cout<<"thread 1"<<endl;
}
 
void*thrd_2(void*arg)
{
    pthread_mutex_lock(&qlock);
    x=20;
    y=10;
    cout<<"has change x and y"<<endl;
    pthread_mutex_unlock(&qlock);
    if(x>y)
    {
        printf("jiangxin  the x is bigger than y\n");
        pthread_cond_signal(&qready);
    }
    cout<<"thread 2"<<endl;
}
 
void*thrd_3(void*arg)
{
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    cout<<"thread 3"<<endl;
}
 
int main(int argc,char**argv)
{
    int err;
    err = pthread_create(&tid1,NULL,thrd_1,NULL);
    if(err!=0)
    {
        cout<<"pthread1 create error"<<endl;
    }
        err = pthread_create(&tid2,NULL,thrd_2,NULL);
    if(err!=0)
    {
        cout<<"pthread2 create error"<<endl;

    }
        err = pthread_create(&tid3,NULL,thrd_3,NULL);
    if(err!=0)
    {
        cout<<"pthread3 create error"<<endl;
    }
    while(1)
    {
        sleep(1);
    }
    return 0;
}