生产者、消费者 POSIX

Producer, consumer POSIX

我正在尝试使用 C POSIX 信号量编写简单的生产者消费者应用程序。 消费者:

int memoryID;
struct wrapper *memory;

int main(int argc, char **argv) {

    srand(time(NULL));
    key_t sharedMemoryKey = ftok(".",MEMORY_KEY);
    if(sharedMemoryKey==-1)
    {
        perror("ftok():");
        exit(1);
    }

    memoryID=shmget(sharedMemoryKey,sizeof(struct wrapper),0);

    if(memoryID==-1)
    {
        perror("shmget(): ");
        exit(1);
    }

    memory = shmat(memoryID,NULL,0);
    if(memory== (void*)-1)
    {
        perror("shmat():");
        exit(1);
    }

    while(1)
    {
        int r = rand();
        sem_wait(&memory->full);
        sem_wait(&memory->mutex);
        int n;
        sem_getvalue(&memory->full,&n);
        printf("Removed item: %d",(memory->array)[n]);
        usleep(1000000);
        sem_post(&memory->mutex);
        sem_post(&memory->empty);
    }

}

制作人:

int memoryID;
struct wrapper *memory;
int rc;

void atexit_function() {
    rc = shmctl(memoryID, IPC_RMID, NULL);
    rc = shmdt(memory);
}

int main(int argc, char **argv) {
    atexit(atexit_function);
    //creating key for shared memory
    srand(time(NULL));
    key_t sharedMemoryKey = ftok(".", MEMORY_KEY);
    if (sharedMemoryKey == -1) {
        perror("ftok():");
        exit(1);
    }

    memoryID = shmget(sharedMemoryKey, sizeof(struct wrapper), IPC_CREAT | 0600);
    if (memoryID == -1) {
        perror("shmget():");
        exit(1);
    }

    memory = shmat(memoryID, NULL, 0);
    if (memory == (void *) -1) {
        perror("shmat():");
        exit(1);
    }

    //initialization
    memset(&memory->array, 0, sizeof(memory->array));
    sem_init(&memory->mutex, 1, 1);
    sem_init(&memory->empty, 1, SIZE_OF_ARRAY);
    sem_init(&memory->full, 1, 0);

    if (memoryID == -1) {
        perror("shmget(): ");
        exit(1);
    }

    while(1)
    {
        int r = rand();
        sem_wait(&memory->empty);
        sem_wait(&memory->mutex);
        int n;
        sem_getvalue(&memory->full,&n);
        printf("Adding task\t Value:%d\tNumber of tasks waiting:%d \n",r,n);
        (memory->array)[n]=r;
        usleep(1000000);
        sem_post(&memory->mutex);
        sem_post(&memory->full);
    }

}

common.h:

#define MEMORY_KEY 5
#define SIZE_OF_ARRAY 10

struct wrapper
{
    int array[SIZE_OF_ARRAY];
    sem_t empty;
    sem_t mutex;
    sem_t full;
};

发生了什么:

生产者正在成功启动

Producer 正在成功添加元素到 table 并在启动 producer 后快速打印出来,

我正在启动消费者消费者不从中获取元素 数组偶数一次

生产者填满数组,正在等待

我真的看不出问题出在哪里。我怀疑问题出在实现而不是算法,因为算法取自维基百科 Link

您的消费者工作正常。它只是不刷新到标准输出。按照 no 的建议,在您的消费者 printf 调用末尾放置一个 \n。您还可以通过等待更长的时间来查看它的工作情况。消费者执行几次迭代后,您的生产者将再次开始生产。