【发布时间】: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_empty、mutex、cnt_filled),但不要在您发布的代码中的任何地方定义它们。另外,signal()和wait()与信号量无关... -
ptr可能是指向shm_structure的指针。您可能希望使用其字段而不是自变量。 -
将
wait(cnt_empty);更改为wait(ptr->cnt_empty);和wait(mutex)更改为wait(ptr->mutex);。 -
@JohnBode 我不确定
wait和signal是他们想要传递sem_t参数的实际函数。