具有C语言信号量的多线程生产者和消费者

时间:2016-10-19 02:03:56

标签: c producer-consumer

我在让项目工作时遇到问题,并希望有人可以提供帮助。准则如下:

你将使用 pthread包创建4个生产者线程和4个消费者线程。每个生产者线程插入 字符'X'进入大小为10,000,000个字符的缓冲区。每个消费者线程删除最近插入的 来自缓冲区的字符。然后每个线程重复该过程

到目前为止,我的代码看起来像这样:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <pthread.h>

#define N 10000000

sem_t mutex;
sem_t full;
sem_t empty;

typedef struct
{
    char const* buf[N];
    char in;
    char out;

} bufferItems;

bufferItems sharedBuffer;


void *producer(void *arg) {

    while(1) {
        sem_wait(&empty);
        sem_wait(&mutex);
        sharedBuffer.buf[sharedBuffer.in] = "X";
        sharedBuffer.in = (sharedBuffer.in+1)%N;
        printf("Producer\n");
        sem_post(&mutex);
        sem_post(&full);


    }

}

void *consumer(void *arg){

    while(1){
        sem_wait(&full);
        sem_wait(&mutex);
        sharedBuffer.buf[sharedBuffer.out] = NULL;
        sharedBuffer.out = (sharedBuffer.out+1)%N;
        printf("Consumer\n");
        sem_post(&mutex);
        sem_post(&empty);

    }

}


int main(void) {

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

    pthread_t p;
    pthread_t c;


    // create four producer threads
    for(int t=0; t<4; t++){
        printf("In main: creating producer thread %d\n", t);
        int err = pthread_create(&p,NULL,producer,NULL);
        if (err){
            printf("ERROR from pthread_create() on producer thread %d\n", err);
            exit(-1);
        }
    }


    // create four consumer threads
    for(int t=0; t<4; t++){
        printf("In main: creating consumer thread %d\n", t);
        int err = pthread_create(&c,NULL,consumer,NULL);
        if (err){
            printf("ERROR; from pthread_create() on consumer thread %d\n", err);
            exit(-1);
        }
    }
}

但是我运行时得到的输出是:

In main: creating producer thread 0
In main: creating producer thread 1
In main: creating producer thread 2
In main: creating producer thread 3
In main: creating consumer thread 0
In main: creating consumer thread 1
In main: creating consumer thread 2
In main: creating consumer thread 3

似乎子线程没有执行,或者信号量不能正常工作,因此存在死锁。任何有关如何使我的代码更好或正常工作的建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

创建所有子线程后,需要在主线程中调用pthread_joinpthread_join等待指定的线程终止。否则主线程将退出并提前取出所有子线程。