C信号量生产者消费者临界区

C semaphore producer-consumer critical section

这是我对信号量的理解:

如果这里有一个名为 sem1 的信号量,并且它后面有一个临界区。然后,一旦输入信号量后的代码,它将完全执行。所以如果你有以下伪代码:

sem_wait(sem1)
  //#CRITICAL SECTION
  //code 1 
  //code 2
sem_post(sem1)

那么代码1、代码2两行都会不停地执行,对吗?即使临界区有 500 行代码也是如此,对吗?

现在,我问这个问题的原因是因为我在以下代码中遇到了一个非常奇怪的错误:

while (1) {
      int binary;
      sem_wait(&shared_mem->bufferUnderflow);
        printf("we passed the underflow\n");
        sem_wait(&shared_mem->binary);
          sem_getvalue(&shared_mem->binary, &binary);
          printf("currentIndex is %d",shared_mem->frontBuffer);
          printf("we passed the binary:%d\n",binary);
          //*****HERE******
            printf("currentIndex is %d",shared_mem->frontBuffer);
            //if we pass here then we can safely take the Job
            Job currentJob = shared_mem->jobs[shared_mem->frontBuffer];
            printf("we took a job");
            int currentIndex = shared_mem->frontBuffer;
            printf("we took currentIndex");
            //change the indeces now that we have popped the latest one
            shared_mem->frontBuffer = (shared_mem->frontBuffer + 1) % sizeBuffer;
            printf("we changed the index");
            //shared_mem->freeIndex = (shared_mem->freeIndex + 1) % sizeBuffer;
        sem_post(&shared_mem->binary);
    sem_post(&shared_mem->bufferOverflow);
    //consume the Job
    printf("Printer starts printing %d pages from Buffer[%d]", (currentJob).pages,currentIndex);
    sleep(currentJob.duration);

}
return 0;
}

在这里,我假设当行 "we passed the binary:0" 被打印时,应该执行此后的所有代码。 但事实并非如此。之后的任何代码 //*****这里****** 不会立即执行。只有当我将其他内容插入生产者的缓冲区时,关键部分的其余部分才会被执行。

抱歉这么久 post。如果有人对可能导致此问题的原因有任何提示,请告诉我。 非常感谢任何帮助!

注意 - 你应该清除 printf() 否则你可能会得出错误的结论。发生 before/after。