使用信号量实现共享内存:代码实现遇到困难求助
Fixing Your Semaphore-Based Producer-Consumer Implementation
Hey there, let's work through the issues in your code and get your producer-consumer setup working properly. First, let's outline the key problems in your current code, then provide a corrected version with clear explanations.
Key Issues in Your Current Code
- Incomplete Code: Your
consumer()call is cut off (consumer()...), and you haven't implemented theproducer(),consumer(),wait(), orsignal()functions you declared. - Non-Atomic Semaphore Simulation: Using regular
intvariables for semaphores (mutex,full,empty) works for a single-threaded demo, but in real multi-threaded environments, these operations aren't atomic—this leads to race conditions. For production use, you'd rely on system-provided semaphores (like POSIXsem_t). - Missing Exit Logic: Your loop runs indefinitely; there's no handling for the
3.Exitoption to break out cleanly. - Critical Section Mismanagement: The
mutexsemaphore isn't being used to wrap the sensitive parts of your producer/consumer logic, which defeats its purpose of protecting shared resources.
Corrected Full Implementation
Here's a complete, working version of your code with all fixes and proper simulation logic:
#include<stdio.h> #include<stdlib.h> // Simulated semaphore variables (for single-threaded demo only) int mutex = 1, full = 0, empty = 3, x = 0; // Wait operation: decrement semaphore to acquire resource int wait(int *sem) { return --(*sem); } // Signal operation: increment semaphore to release resource int signal(int *sem) { return ++(*sem); } // Producer function: adds an item to the buffer void producer() { wait(&mutex); wait(&empty); x++; printf("\nProducer produced item %d", x); signal(&full); signal(&mutex); } // Consumer function: removes an item from the buffer void consumer() { wait(&mutex); wait(&full); printf("\nConsumer consumed item %d", x); x--; signal(&empty); signal(&mutex); } int main() { int n; printf("\n1.Producer\n2.Consumer\n3.Exit"); while(1) { printf("\nEnter your choice:"); scanf("%d", &n); switch(n) { case 1: if((mutex == 1) && (empty != 0)) producer(); else printf("\nBuffer is full!!"); break; case 2: if((mutex == 1) && (full != 0)) consumer(); else printf("\nBuffer is empty!!"); break; case 3: printf("\nExiting program..."); exit(0); // Cleanly terminate the program default: printf("\nInvalid choice! Please enter 1, 2, or 3."); } } return 0; }
Key Explanations
- Wait/Signal Logic: The
wait()function grabs a semaphore (decrements its value) to access a resource, whilesignal()releases it (increments the value). For multi-threaded code, replace these with atomic system calls likesem_wait()andsem_post()(from<semaphore.h>for POSIX systems). - Critical Section Protection: The
mutexsemaphore ensures only one producer or consumer can modify the shared buffer (x) at a time—we callwait(&mutex)before touching the buffer andsignal(&mutex)afterward to release access. - Buffer State Tracking:
emptycounts available buffer slots; producers decrement it when adding items.fullcounts filled buffer slots; consumers decrement it when removing items.
- Exit Handling: The
case 3now usesexit(0)to terminate the program properly when the user chooses to exit.
Note for Real-World Use
If you plan to run this in a multi-threaded environment, replace the integer semaphores with POSIX or Windows native semaphores. Regular integers can cause race conditions because increment/decrement operations aren't atomic across threads.
内容的提问来源于stack exchange,提问作者j. Doe
相关产品推荐
相关产品推荐

