c - 使用信号量的有界缓冲区生产者-消费者代码

标签 c synchronization pthreads semaphore producer-consumer

使用信号量的临界区的整个实现是我试图实现的。 显示了使用信号量的完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

int buf[256];
int in = 0;
int out = 0;
sem_t full;
sem_t empty;
sem_t mutex;
int buf_size;
int counter = 0;

void *producer(void *arg)
{
    int i, item, *index;
    index = (int *)arg;
    for (i = 0;; i++)
    {
        item = 1000 + i;
        sem_wait(&empty);
        sem_wait(&mutex);
        buf[in] = item;
        in = (in + 1) % (*index);
        counter++;
        printf("\n%d [P%d] ", item, *index);
        sem_post(&mutex);
        sem_post(&full);
        /* if (i % 5 == 0)
            sleep(1); */
    }
}

void *consumer(void *arg)
{
    int i, item, *index;
    index = (int *)arg;
    for (i = 0;;i++)
    {
        sem_wait(&full);
        sem_wait(&mutex);
        item = buf[out];
        out = (out + 1) % (*index);
        counter--;
        printf("\n%d [C%d] ", item, *index);
        sem_post(&mutex);
        sem_post(&empty);
        /* if (i % 5 == 0)
            sleep(1); */
    }
}

int main()
{
    int produce, consume;
    int i;
    printf("\nThe Buffer Size:");
    scanf("%d", &buf_size);
    printf("\nThe Producer:");
    scanf("%d", &produce);
    printf("\nThe Consumer:");
    scanf("%d", &consume);
    pthread_t prod, cons;
    void* exit_status;
    sem_init(&full, 0, 0);
    sem_init(&empty, 0, buf_size);
    sem_init(&mutex, 0, 1);
    for (i = 0; i < produce; i++)
    {
        pthread_create(&prod, NULL, producer, &i);
    }
    for (i = 0; i < consume; i++)
    {
        pthread_create(&cons, NULL, consumer, &i);
    }
    pthread_join(prod, &exit_status);
    pthread_join(cons, &exit_status);
    // pthread_exit(NULL);
    return 0;
}

代码编译没有错误,但输出只是它接受的输入,然后它只显示 1000 和 p1 1001 p2 以及类似的值

最佳答案

您创建了您的第一个生产者,然后立即等待它用 join() 终止,因此阻塞了您的主线程。该生产者在其 for 循环中运行,插入队列直到“空”信号量没有更多单元,然后生产者阻塞。

主线程和一个生产者线程现在都卡住了。其他生产者和所有消费者从未启动。没有消费者意味着没有任何东西可以从队列中弹出,所以整个过程都陷入了僵局。

这在使用 join() 时并不少见。

关于c - 使用信号量的有界缓冲区生产者-消费者代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22807493/

相关文章:

multithreading - 线程安全的数据结构设计

c - pthread_mutex_unlock 不是原子的

c - 为什么我的 C 编译器找不到一些头文件?

c - 如何使 GCC 编译以便二进制文件使用新的共享对象?

Visual Studio 可以用来运行带有 ARM 脚本的 C 代码吗?

c++ - C++中的Pthread取消

c - pthread_getschedparam 函数的奇怪行为

c - 使用 strcat 超过 1 次 - link2019

javascript - 修改后如何存储javascript

java - 我可以用纯 Java 实现 park/unpark 方法吗?