为什么在结构中声明“未声明的互斥体”错误时会出现?

时间:2019-04-02 20:44:37

标签: c mutex semaphore

我正在使用信号量创建生产者和使用者文件以进行同步。我创建了一个结构,在其中定义sem_t变量。 sem_t变量之一是互斥体。 Mutex代表互斥。但是,在编译代码时说“ mutex”未声明时会出错。自从我以为我在结构中声明它以来,这对我来说就没有了。

我尝试将变量初始化为值1,并使用其他方法在其中使用该变量,例如sem_wait()和wait()。

#define BUFFER_SIZE 10
typedef struct{
    int buffer[BUFFER_SIZE];
    int in;
    int out;
    sem_t mutex;
    sem_t cnt_filled;
    sem_t cnt_empty;
} shm_structure;
/* pointer to shared memory object */
shm_structure *ptr;

ptr->in = ptr->out = 0;

    fp = fopen("input.txt", "r");
    //cnt_empty = 
    //mutex = 1;

    do {
        /* produce an item in next_produced */

        while(((ptr-> in + 1) % BUFFER_SIZE) == ptr->out) {
            ; // do nothing
        }

        wait(cnt_empty);
        wait(mutex);

        if(fscanf(fp, "%d", &item) != EOF) {
            ptr->buffer[ptr->in]= item;
            printf("%s Read %d from the file\n", get_time(), item);
            ptr->in = (ptr->in + 1) % BUFFER_SIZE; //increment tell the end of the file
        } else {
            break;
        }

        /* add next_produced into the buffer */

        signal(mutex);
        signal(cnt_filled);
        //sem_post(mutex);
        //sem_post(cnt_filled);

    } while(1);

    fclose(fp);

    return 0;

我的代码在编译时应该没有错误。那是我目前想要的唯一结果。

2 个答案:

答案 0 :(得分:1)

声明结构时,您正在定义聚合数据类型。现在,您需要创建此结构的实例,然后可以访问该结构的成员。有关如何使用结构成员的基本示例:

typedef struct{
    int x;
    int y;
} my_struct;

my_struct my_instance_of_struct;
my_instance_of_struct.x = 1;

答案 1 :(得分:0)

    signal(mutex);

由于未声明mutex,因此您会在此处收到错误消息。相反,您必须执行shm_structure.mutex