gpt4 book ai didi

c - 两个函数之间的 Malloc 可访问性

转载 作者:太空宇宙 更新时间:2023-11-04 04:51:10 24 4
gpt4 key购买 nike

我正在编写多线程生产者-消费者问题的变体。我正在尝试使用队列来存储“生产”的元素,直到它们稍后被“消耗”。我的问题是,当消费者线程运行时,它只处理添加到队列中的最新项目(而不是队列中最旧的项目)。此外,它会重复处理该项目(直到队列本身的项目数)。

我认为我的问题可能是当我将一个项目插入队列时我需要分配一些内存(虽然我不确定)。但是,当该项目即将被消费时,我需要一种方法来引用此内存。

无论如何,这是我的程序的配对版本。我意识到我在这里发布的内容不完整(这是一个无限循环),但我只是想展示与这个问题相关的部分。函数 queue_push() 和 queue_pop() 已经过良好测试,所以我认为问题不在于此。如果需要,我会发布更多内容。

谁能看出为什么我的消费者线程只处理最新的队列项?谢谢!

sem_t mutex;
queue q;

FILE* inputFPtr[10];

char host_in[BUFFERSIZE];
char host_out[BUFFERSIZE];

void* p(void* inputFile) {

while (fscanf(inputFile, INPUTFS, host_in) > 0)
{
sem_wait(&mutex);
queue_push(&q, host_in); //this function pushes the hostname onto the back of the queue
fprintf(stdout, "Produced: %d) %s\n", i, host_in);
sem_post(&mutex);
}

fclose (inputFile);
}

void* c() {

while (TRUE)
{
sem_wait(&mutex);
sprintf(hostname_out, "%s", (char *) queue_pop(&q));
printf("%s\n", host_out);
sem_post(&mutex);
}

}

int main (int argc, char* argv[]) {

int i;
pthread_t *th_in[argc-2];
pthread_t *th_out[2];

for (i = 0; i < (argc-2); i++) {
th_in[i] = (pthread_t *) malloc(sizeof(pthread_t));
inputFPtr[i] = fopen(argv[i+1], "r");
pthread_create (th_in[i], NULL, p, inputFPtr[i]);
}

for (i = 0; i < 2; i++) {
th_out[i] = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create (th_out[i], NULL, c, null);
}

for (i = 0; i < (argc - 2); i++) {
pthread_join(*th_in[i], 0);
free(th_in[i]);
}

for (i = 0; i < (2); i++) {
pthread_join(*th_out[i], 0);
free(th_out[i]);
}

return EXIT_SUCCESS;
}

最佳答案

您忘记发布代码了。但是根据您的描述,似乎所有队列成员都指向同一个内存块。这就是为什么你所有的流行音乐都会产生相同的项目。你的问题的答案是肯定的。您需要为每个项目分配内存并在“消耗”后释放它。

尝试发布一些代码以获得更具体的答案...

关于c - 两个函数之间的 Malloc 可访问性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15072569/

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