【问题标题】:Why does 'undeclared mutex' error show up when it is declared in struct?为什么在struct中声明时会出现“未声明的互斥锁”错误?
【发布时间】:2019-08-24 06:45:10
【问题描述】:

我正在使用信号量创建生产者和消费者文件以进行同步。我创建了一个定义 sem_t 变量的结构。 sem_t 变量之一是互斥锁。 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;

我的代码在编译时应该没有错误。这是我目前正在寻找的唯一结果。

【问题讨论】:

  • 您应该从该结构的实例访问它。
  • 就像错误所说的那样,您有变量(cnt_emptymutexcnt_filled),但不要在您发布的代码中的任何地方定义它们。另外,signal()wait() 与信号量无关...
  • ptr 可能是指向shm_structure 的指针。您可能希望使用其字段而不是自变量。
  • wait(cnt_empty); 更改为wait(ptr->cnt_empty);wait(mutex) 更改为wait(ptr->mutex);
  • @JohnBode 我不确定waitsignal 是他们想要传递sem_t 参数的实际函数。

标签: c mutex semaphore


【解决方案1】:

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

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

my_struct my_instance_of_struct;
my_instance_of_struct.x = 1;

【讨论】:

  • 谢谢。这解决了未声明的互斥锁问题。但是,您知道为什么我知道“分配中的类型不兼容”错误吗? my_instance_of_struct.mutex = 1 似乎是兼容的,因为它只是使用 struct 实例的 struct 中的一个变量。
  • 我建议您查看 Shawn 对您的问题的 cmets,它指出 ptr 可能是指向您的结构实例的指针。之后,我建议阅读 POSIX 信号量的文档。我的回答并不是专门针对信号量的使用,而是针对访问结构成员。
【解决方案2】:
    signal(mutex);

您在此处收到错误消息,因为未声明 mutex。相反,您必须这样做shm_structure.mutex

【讨论】:

  • "你必须这样做shm_structure.mutex"好吧,不。我相信你知道。请在回答时更准确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2015-02-20
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多