制片人,消费者POSIX

时间:2015-05-07 23:21:45

标签: c concurrency posix ipc

我正在尝试使用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;
};

发生了什么:

制作人正在成功启动

生产者成功地向表添加元素并在启动生产者后快速打印出来

我正在开始消费者消费者不接受元素     阵列甚至一次

制作人填满阵列并等待

我真的不知道问题出在哪里。我怀疑问题是实现而不是算法导致算法取自维基百科Link

1 个答案:

答案 0 :(得分:1)

您的消费者工作正常。它只是没有冲到stdout。通过在消费者\n电话结束时添加printf来建议。你也可以通过等待更长时间来看它的工作原理。在消费者执行了几次迭代后,您的生产者将再次开始生产。