【发布时间】:2017-03-15 22:10:04
【问题描述】:
这是我的基本代码,现在的问题是它运行了几个循环,然后给出了分段错误。现在我知道分段错误是由于在内存位置非法读/写造成的,但我没有在该笔记上使用任何指针。
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<pthread.h>
#include<stdlib.h>
int counter = 0;
int BUFFER_SIZE = 5;
int buffer[] = {0};
int in = 0;
int out = 0;
void *prod(char);
void *cons(void);
bool flag = true;
void main()
{ int i, j;
pthread_t thread1, thread2;
do{
flag = true;
i = pthread_create(&thread1, NULL, prod('i'), NULL);
flag = true;
j = pthread_create(&thread2, NULL, cons(), NULL);
}while(1);
}
void* prod(char a)
{
while (flag) {
printf("\nCounter = %d", counter);
while (counter == BUFFER_SIZE) {
printf("\nBusy Waiting!!!");
}
buffer[in] = a;
in = (in + 1) % BUFFER_SIZE;
printf("\nProducer produced an item %c!",a);
counter++;
printf("\nTotal items produced = %d",counter);
flag = false;
}
}
void* cons()
{
char a;
while (flag) {
printf("\nCounter = %d",counter);
while (counter == 0){printf("\nBusy Waiting!!!");
}
a = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
printf("\nTotal items remaining = %d",counter);
flag = false;
}
}
【问题讨论】:
-
您正在创建无限多的线程。准确地说,每次迭代两次。
-
但我得到的错误是在函数调用@StoryTeller 1 或 2 次之后
-
不,您在看到输入大约两次后才知道。线程创建可以比这快得多。这是你的程序的一个大错误。
-
为什么
prod和cons缺少return语句? -
您需要提供一个指向线程过程的函数指针,而您的代码调用这些函数 (
cons()) 并将它们的结果用作指向线程函数的指针。 cons 和 prod 都不返回任何使返回值未定义的东西。当 pthread_create 使用这样的函数指针启动一个线程时,它只会崩溃。
标签: c producer-consumer producer