我正在尝试使用带有gcc的Codeblocks IDE在C中进行并发编程。当我运行我的程序时,我没有收到任何输出。有趣的是,当我在程序中的某个点放置一个断点时,程序将执行所有指令(包括向控制台输出值)直到那一点。但是,之后,如果我尝试执行指令srand(time(NULL))
,我正在观看的所有变量都会立即显示“读取变量时出错,无法访问地址X处的内存”,调试过程将停止。
这是我的main()函数
/*main function*/
int main()
{
int k = 3;
int m = 100;
int n = 10;
int t = 10;
/*First, let's create the threads*/
pthread_t thread[numOfThreads];
/*Second, create the data struct*/
struct programData *data = malloc(sizeof(struct programData));
/*Initialize data struct*/
data->kPumps=k;
data->mVisitors=m;
data->nCars=n;
data->tTime=t; /*They'll drive visitor around for 10 units of time.*/
/*Now let's create the different threads*/
pthread_create(&thread[0], NULL, visitorThread, (void*)data);
pthread_create(&thread[1], NULL, carThread, (void*)data);
pthread_create(&thread[2], NULL, pumpThread, (void*)data);
pthread_create(&thread[3], NULL, gasTruck, (void*)data);
return 0;
}
我的访客帖子
void *visitorThread(void *arg){
int arrayIndex;
int i;
/*Let's create mVisitors*/
struct programData *data;
data = (struct programData*)arg;
int numOfVisitors;
numOfVisitors = data->mVisitors;
/*create an array of visitors*/
struct visitor v[numOfVisitors];
/*Initialize values*/
for(i = 0; i < numOfVisitors; i++){
v[i].id = i+1;
v[i].isInCar = false;
v[i].isInQueue = false;
}
printf("There are %d visitors at the San Diego Zoo \n", numOfVisitors);
printf("At first the visitors wait at the snake exhibit \n");
//sleep(5);
printf("Now some of them are getting bored, and want to get into a car to be shown the rest of the zoo \n");
/*After a random amount of time, some people line up to take cars*/
/*create queue*/
struct visitor* queue[numOfVisitors];
/*Initialize the array*/
for(i = 0; i < numOfVisitors; i++){
queue[i] = NULL;
}
arrayIndex = 0;
/*While there are people in the snake exhibit*/
while(numOfVisitors >=1){
/*After a random period of time, no more than 5 seconds...*/
//srand
srand(time(NULL));
int timeBeforePersonLeaves = rand()%5+1;
//fflush(stdout);
//sleep(timeBeforePersonLeaves);
/*...a random person will get bored and enter the array line to be picked up by a car*/
srand(time(NULL));
int personIndex = rand() % numOfVisitors;
queue[arrayIndex] = &v[personIndex];
v[personIndex].isInQueue = true;
printf("Visitor %d is now in queue spot %d \n", personIndex, arrayIndex);
arrayIndex++;
}
return;
}
问题似乎存在于while循环中。如果我在while循环的末尾在括号处放置一个断点,它将输出每个值。但是,如果将断点放在while循环中的任何位置,一旦它到达srand调用,就会导致同样的问题。任何有关这方面的帮助将不胜感激,并提前感谢。
答案 0 :(得分:0)
while(numOfVisitors >=1)
。你有一个infinete循环。 arrayIndex
中的结果不断增长且溢出queue
。另外,请阅读srand的手册页。你只需要连续打电话一次。
- kaylum