需要帮助消费者/生产者共享内存和信号量(c语言)

时间:2015-12-08 12:52:34

标签: c

如果我运行代码,我得不到任何结果。如果我删除了sem_postsem_wait,那么它就可以了。我有一个生产者/消费者应用程序,它通过共享内存交换数据。

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <dispatch/dispatch.h>
#include <errno.h>
#include <math.h>

int shmid;
unsigned long long Fibonacci(int n);
typedef struct node_t {
  unsigned long long data;
  int n;
  bool set;
  int id;
} node_t;

typedef struct fibobuff_t {
   char szFiboText[BUFF_SIZE / 2];
   struct node_t naNode[MAX_BUF];
} fibobuff_t;

#define MAX_BUF 5
#define SHM_SIZE 65365
#define BUFF_SIZE 65536

sem_t *empty;
sem_t *full;

void producer(){
    int n =0, i =0;
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);
    if(pFB == NULL){
        perror("error");
        exit(1);
    }
    while (true) {
        printf("(%i) Waiting for room... ", i);
        sem_wait(empty);  
        usleep(150 + rand() % 1350);   

        pFB->naNode[i].data = Fibonacci(n++);
        sem_post(full);
        i = (i + 1) % (MAX_BUF);
        if (pFB->naNode[i].set){
            //  sem_wait(empty);
        }
    }
}

void consumer(){
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);
    int i = 0;
    while (true) { 
        printf("(%i) Waiting for content... ", i);
        sem_wait(full);

        usleep(150 + rand() % 1600);
        char szTmp[BUFF_SIZE/2] = {0};
        snprintf(szTmp, BUFF_SIZE/2, "%llu ", pFB->naNode[i].data);
        strncat(pFB->szFiboText,szTmp, BUFF_SIZE/2);
        pFB->naNode[i].set = FALSE;
        printf("\tNr. %i = %s\n\n", pFB->naNode[i].n, szTmp);
        i = (i + 1) % (BUFF_SIZE);
        sem_post(empty);
        //sem_post(pmut);
        if (!pFB->naNode[i].set){
            sem_wait(full);
        }
    }
}

int main(void)
{
    int t;
    if ((shmid = shmget(IPC_PRIVATE, BUFF_SIZE, 0666 | IPC_CREAT)) == -1) {
        perror("shmget consumer");
        exit(1);
    }
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);

    for (t = 0; t < MAX_BUF; t++) {
        pFB->naNode[t].data = 0;
    }
    empty = sem_open("/empty",O_CREAT,0644,1);
    full = sem_open("/full",O_CREAT,0644,0);

    if(fork()){
        producer(); 
    }else{
        consumer();
    }
}
有人可以提供帮助。我不知道出了什么问题

1 个答案:

答案 0 :(得分:0)

  • consumer()中,您有两次拨打sem_wait(full);放下第二个。

  • consumer() i = (i + 1) % (BUFF_SIZE); i = (i + 1) % MAX_BUF正确的是sem_unlink()

  • 请注意,程序的后续运行可能与第一次运行的行为不同,因为您不会按message House { message room { string name = 1; int32 windows = 2; int32 doors = 3; } string address = 1; repeated room rooms = 2; } 删除信号量,并且在创建时会设置它们的初始值。

    < / LI>