当前位置:   article > 正文

生产者消费者模型_#include #include #define n

#include #include #define n 10 typedef int semaphore;
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

#define MAXSIZE 10
typedef int ElemType;

struct queue_type
{
    ElemType buff[MAXSIZE];
    ElemType front;
    ElemType rear;
}Q;

pthread_mutex_t mutex;
sem_t sem_one;
sem_t sem_two;

void initial_queue(struct queue_type *q)
{
    int i;
    for (i = 0; i < MAXSIZE; i++)
    {
        q->buff[i] = 0;
    }
    q->front = 0;
    q->rear = 0;

}

void *producer()
{
    int i, num;

    printf("the number to produce: \n");
    scanf("%d", &num);

    pthread_mutex_lock(&mutex);

    for (i = 0; i < num; i++)
    {
        sem_wait(&sem_two);
        Q.buff[Q.rear] = 1;
        Q.rear = (Q.rear + 1) % MAXSIZE;
        sem_post(&sem_one);
    }

    pthread_mutex_unlock(&mutex);
    return NULL;
}

void *consumer()
{
    int i, num;

    printf("the number to consume: \n");
    scanf("%d", &num);

    pthread_mutex_lock(&mutex);

    for (i = 0; i < num; i++)
    {
        sem_wait(&sem_one);
        Q.buff[Q.front] = 0;
        Q.front = (Q.front + 1) % MAXSIZE;
        sem_post(&sem_two);
    }

    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main()
{
    int i;
    pthread_t id_p, id_c;
    initial_queue(&Q);

    pthread_mutex_init(&mutex, NULL);
    sem_init(&sem_one, 0, 0);
    sem_init(&sem_two, 0, MAXSIZE);

    pthread_create(&id_p, NULL, producer, NULL);
    pthread_join(id_p, NULL);

    pthread_create(&id_c, NULL, consumer, NULL);
    pthread_join(id_c, NULL);

    pthread_mutex_destroy(&mutex);
    sem_destroy(&sem_one);
    sem_destroy(&sem_two);

    printf("front : %d\n", Q.front);
    printf("rear : %d\n", Q.rear);
    for (i = 0; i < MAXSIZE; i++)
        printf("%d  ", Q.buff[i]);
    printf("\n");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/267890
推荐阅读
相关标签
  

闽ICP备14008679号