我们是否应该将互斥量与信号量一起使用以进行正确的同步并防止出现竞争状况?

时间:2018-09-01 18:04:37

标签: pthreads mutex semaphore

我试图查看竞争状况发生在消费者与生产者的问题上, 所以我让多个生产者和多个消费者。

据我所知,我需要为互斥量提供信号量: 相互竞争的条件下使用互斥,因为多个生成器可以同时访问缓冲区。则数据可能已损坏。

信号量在生产者和消费者之间提供信号

这里的问题是,当我不使用Mutex时(我仅使用信号量),同步会正确发生。我的理解是正确的还是下面的代码有什么错误要做?

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

int buffer;
int loops = 0;

sem_t empty;
sem_t full;
sem_t mutex; //Adding MUTEX

void put(int value) {
    buffer = value;       
}

int get() {
    int b = buffer;      
    return b;
}



void *producer(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        sem_wait(&empty);

        //sem_wait(&mutex);
        put(i);
        //printf("Data Set from %s, Data=%d\n", (char*) arg, i);
        //sem_post(&mutex);

        sem_post(&full);
    }
}

void *consumer(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        sem_wait(&full);

        //sem_wait(&mutex);
        int b = get();
        //printf("Data recieved from %s, %d\n", (char*) arg, b);
        printf("%d\n", b);
        //sem_post(&mutex);

        sem_post(&empty);

    }
}

int main(int argc, char *argv[])
{
    if(argc < 2 ){
        printf("Needs 2nd arg for loop count variable.\n");
        return 1;
    }

    loops = atoi(argv[1]);

    sem_init(&empty, 0, 1); 
    sem_init(&full, 0, 0);    
    sem_init(&mutex, 0, 1);

    pthread_t pThreads[3];
    pthread_t cThreads[3];


    pthread_create(&cThreads[0], 0, consumer, (void*)"Consumer1");
    pthread_create(&cThreads[1], 0, consumer, (void*)"Consumer2");
    pthread_create(&cThreads[2], 0, consumer, (void*)"Consumer3");

    //Passing the name of the thread as paramter, Ignore attr
    pthread_create(&pThreads[0], 0, producer, (void*)"Producer1");
    pthread_create(&pThreads[1], 0, producer, (void*)"Producer2");
    pthread_create(&pThreads[2], 0, producer, (void*)"Producer3");


    pthread_join(pThreads[0], NULL);
    pthread_join(pThreads[1], NULL);
    pthread_join(pThreads[2], NULL);

    pthread_join(cThreads[0], NULL);
    pthread_join(cThreads[1], NULL);
    pthread_join(cThreads[2], NULL);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

我相信我已经解决了问题。这是发生了什么

初始化信号量时,请将empty的线程数设置为1,将full的线程数设置为0

sem_init(&empty, 0, 1); 
sem_init(&full, 0, 0);    
sem_init(&mutex, 0, 1);

这意味着线程只有一个“空间”可以进入临界区域。换句话说,您的程序正在做的是

produce (empty is now 0, full has 1)
consume (full is now 0, empty has 0)
produce (empty is now 0, full has 1)
...

就好像您有一个令牌(或者,如果愿意的话,是一个互斥锁),并且您在消费者和生产者之间传递了该令牌。这实际上是消费者—生产者问题的全部原因,只是在大多数情况下,我们担心让多个消费者和生产者同时工作(这意味着您拥有多个令牌)。在这里,由于您只有一个令牌,因此您基本上拥有了一个互斥量。

希望对您有所帮助:)