pthread_cond_wait条件变量的使用

2018-08-02  本文已影响15人  动感新势力fan

pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,然后阻塞在等待队列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx); 再读取资源

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int sequence=1;
int eat = 1;
pthread_mutex_t productor_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t my_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t productor_mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t my_cond1 = PTHREAD_COND_INITIALIZER;

void *productor1()
{
    int my_sequence = 1;

    while(1)
    {
        pthread_mutex_lock(&productor_mutex);
        while(sequence!=my_sequence)
        {
            pthread_cond_wait (&my_cond, &productor_mutex);
        }


        pthread_mutex_lock(&productor_mutex1);
        while(eat!=1)
        {
            pthread_cond_wait (&my_cond1, &productor_mutex1);
        }
        printf("A ");

        eat=0;
        pthread_cond_broadcast (&my_cond1);
        pthread_mutex_unlock (&productor_mutex1);

        sequence=2;
        pthread_cond_broadcast(&my_cond);
        pthread_mutex_unlock (&productor_mutex);
    }

    return 0;
}

void *productor2()
{
    int my_sequence=2;

    while(1)
    {
        pthread_mutex_lock(&productor_mutex);
        while(sequence!=my_sequence)
        {
            pthread_cond_wait (&my_cond, &productor_mutex);
    }

        pthread_mutex_lock(&productor_mutex1);
        while(eat!=1)
        {
        pthread_cond_wait (&my_cond1, &productor_mutex1);
        }
        printf("B ");

        eat=0;
        pthread_cond_broadcast (&my_cond1);
        pthread_mutex_unlock (&productor_mutex1);

        sequence=1;
        pthread_cond_broadcast (&my_cond);
        pthread_mutex_unlock (&productor_mutex);
    }

    return 0;
}

void *consumer()
{
    long a=200;

    while(a--)
    {
        pthread_mutex_lock(&productor_mutex1);
        while(eat!=0)
        {
            pthread_cond_wait (&my_cond1, &productor_mutex1);
        }
        printf("C ");

        eat=1;
        pthread_cond_broadcast (&my_cond1);
        pthread_mutex_unlock (&productor_mutex1);
    }

    return 0;
}

int main(void)
{
    pthread_t pth1=0,pth2=0,pth3=0;
    int err=-1;
    void *tret=NULL;

    err = pthread_create(&pth1,NULL,productor1,NULL);
    if(err)
    {
        printf("creat pthread productor failed!\n");
        exit(1);
    }
    err = pthread_create(&pth2,NULL,productor2,NULL);
    if(err)
    {
        printf("creat pthread productor failed!\n");
        exit(1);
    }

    err = pthread_create(&pth3,NULL,consumer,NULL);
    if(err)
    {
        printf("creat pthread consumer failed!\n");
        exit(1);
    }

    err = pthread_join(pth3,&tret);
    if(err)
        printf("can't join pthread consumer!\n");
    else
            printf("pthread consumer exit with %d!\n",(int)tret);

    pthread_cancel(pth1);
    pthread_cancel(pth2);
    exit(0);
}

上一篇下一篇

猜你喜欢

热点阅读