You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用信号量实现共享内存:代码实现遇到困难求助

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 the producer(), consumer(), wait(), or signal() functions you declared.
  • Non-Atomic Semaphore Simulation: Using regular int variables 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 POSIX sem_t).
  • Missing Exit Logic: Your loop runs indefinitely; there's no handling for the 3.Exit option to break out cleanly.
  • Critical Section Mismanagement: The mutex semaphore 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, while signal() releases it (increments the value). For multi-threaded code, replace these with atomic system calls like sem_wait() and sem_post() (from <semaphore.h> for POSIX systems).
  • Critical Section Protection: The mutex semaphore ensures only one producer or consumer can modify the shared buffer (x) at a time—we call wait(&mutex) before touching the buffer and signal(&mutex) afterward to release access.
  • Buffer State Tracking:
    • empty counts available buffer slots; producers decrement it when adding items.
    • full counts filled buffer slots; consumers decrement it when removing items.
  • Exit Handling: The case 3 now uses exit(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:56:34