gpt4 book ai didi

c - C 中的生产者消费者程序 - 段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 19:08:30 26 4
gpt4 key购买 nike

嗨,我对 C 编程有点陌生。面临生产者消费者问题。当我尝试运行下面的代码时,我会遇到段错误(核心转储)。请建议我哪里出错了。但这段代码适用于一个消费者,但对于多个消费者,它会抛出错误。

代码:

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

#define MAXNITEMS 20
#define MAXNTHREADS 5
void *produce(void *arg);
void *consume(void *arg);
/* globals shared by threads */
int nitems=MAXNITEMS; /* read-only by producer and consumer */
int buff[MAXNITEMS];
int Nsignals;

struct {
pthread_mutex_t mutex;
int buff[MAXNITEMS];
int nput; /* next index to store */
int nval; /* next value to store */
} put = { PTHREAD_MUTEX_INITIALIZER };
/** struct put is used by producer only ***/
struct{
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready; /* number ready for consumer */
} nready = {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,0};

int main(int argc, char **argv)
{
int i, prod, con;
pthread_t tid_produce[MAXNTHREADS], tid_consume[MAXNTHREADS];
printf("Enter the number of producers : \n");
scanf("%d",&prod);
printf("Enter the number of consumers: \n");
scanf("%d",&con);
/* create all producers and consumers */
for (i = 0; i < prod; i++)
{
printf("1 %d\n", i);
pthread_create(&tid_produce[i], NULL,produce, NULL);
}
for (i = 0; i < con; i++) {
printf("2 %d\n", i);
pthread_create(&tid_consume[i], NULL, consume, NULL);
}
for (i = 0; i < prod; i++) {
printf("3 %d\n", i);
pthread_join(tid_produce[i], NULL);
}
for (i = 0; i < con; i++) {
printf("4 %d\n", i);
pthread_join(tid_consume[i], NULL);
}
exit(0);
}

void *produce(void *arg)
{
for ( ; ; )
{
pthread_mutex_lock(&put.mutex);
if (put.nput >= nitems) {
pthread_mutex_unlock(&put.mutex);
return(NULL); /* array is full, we're done */
}
put.buff[put.nput] = put.nval;
printf ("producer %lu produced :%d \n",pthread_self(), put.buff[put.nput]);
put.nput++;
put.nval++;
printf("outside producer lock\n");
pthread_mutex_unlock(&put.mutex);
*((int *) arg) += 1;
}
}

void *consume(void *arg)
{
int i;
for (i = 0; i < nitems; i++) {
pthread_mutex_lock(&nready.mutex);
while (nready.nready == 0){
pthread_cond_wait(&nready.cond,&nready.mutex);
}
printf ("consumer %lu consumed %d \n", pthread_self(),nready.nready);
nready.nready--;
pthread_mutex_unlock(&nready.mutex);

if (buff[i] != i)
printf("buff[%d] = %d\n", i, buff[i]);
}
return(NULL);
}

最佳答案

product(...) 内的

*((int *) arg) += 1 会导致段错误。因为 pthread_create(&tid_ Produce[i], NULL,product, NULL);NULL 作为 arg 传递。

所以我们需要为arg分配一些内存。

// main
int i, prod, con;
pthread_t tid_produce[MAXNTHREADS], tid_consume[MAXNTHREADS];
int p_arg[MAXNTHREADS]; // <======
// ...
for (i = 0; i < prod; i++)
{
pthread_create(&tid_produce[i], NULL,produce, p_arg+i); // <====
}

关于c - C 中的生产者消费者程序 - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093729/

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