gpt4 book ai didi

c - C 中使用信号量的多线程生产者和消费者

转载 作者:行者123 更新时间:2023-11-30 15:04:50 25 4
gpt4 key购买 nike

我在项目运行时遇到问题,希望有人能够提供帮助。指导原则如下:

您将使用pthread 包创建 4 个生产者线程和 4 个消费者线程。每个生产者线程插入将字符“X”放入大小为 10,000,000 个字符的缓冲区中。每个消费者线程都会删除最近插入的来自缓冲区的字符。然后每个线程重复该过程

到目前为止,我的代码如下所示:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <pthread.h>

#define N 10000000

sem_t mutex;
sem_t full;
sem_t empty;

typedef struct
{
char const* buf[N];
char in;
char out;

} bufferItems;

bufferItems sharedBuffer;


void *producer(void *arg) {

while(1) {
sem_wait(&empty);
sem_wait(&mutex);
sharedBuffer.buf[sharedBuffer.in] = "X";
sharedBuffer.in = (sharedBuffer.in+1)%N;
printf("Producer\n");
sem_post(&mutex);
sem_post(&full);


}

}

void *consumer(void *arg){

while(1){
sem_wait(&full);
sem_wait(&mutex);
sharedBuffer.buf[sharedBuffer.out] = NULL;
sharedBuffer.out = (sharedBuffer.out+1)%N;
printf("Consumer\n");
sem_post(&mutex);
sem_post(&empty);

}

}


int main(void) {

sem_init(&mutex, 0, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, N);

pthread_t p;
pthread_t c;


// create four producer threads
for(int t=0; t<4; t++){
printf("In main: creating producer thread %d\n", t);
int err = pthread_create(&p,NULL,producer,NULL);
if (err){
printf("ERROR from pthread_create() on producer thread %d\n", err);
exit(-1);
}
}


// create four consumer threads
for(int t=0; t<4; t++){
printf("In main: creating consumer thread %d\n", t);
int err = pthread_create(&c,NULL,consumer,NULL);
if (err){
printf("ERROR; from pthread_create() on consumer thread %d\n", err);
exit(-1);
}
}
}

但是我运行它时得到的输出是这样的:

In main: creating producer thread 0
In main: creating producer thread 1
In main: creating producer thread 2
In main: creating producer thread 3
In main: creating consumer thread 0
In main: creating consumer thread 1
In main: creating consumer thread 2
In main: creating consumer thread 3

似乎子线程没有执行,或者信号量没有正常工作,因此出现死锁。任何有关如何使我的代码更好或正常工作的建议将不胜感激。

最佳答案

您需要调用pthread_join创建所有子线程后在主线程中。 pthread_join 等待指定线程终止。否则主线程将退出并过早取出所有子线程。

关于c - C 中使用信号量的多线程生产者和消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40120882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com