Sossenbinder
Sossenbinder

Reputation: 5302

Why is my for loop becoming an infinite loop here?

I have this code right now:

void performAction(int n){
  int i;
  int returnValue;
  pthread_t p;

  for(i=1; i < n; i++){
    printf("Iteration %d",i);
    pthread_create(&p, NULL, donothing, NULL);
    pthread_join(p, (void**)&returnValue);
    if(returnValue == 0){
      printf("Terminated");
    }
  }
}

void* donothing(){
  pthread_exit ((void*)0);
}

My task is to start n processes with pthread create and immediately join them, to wait for their termination.

I get to the printf("Terminated"); after every "Iteration %d", but it never seems to increment.

Right now all I get is an infinite loop of this output:

Iteration 1
Terminated
Iteration 1
Terminated
...

Why is this a infinite loop here? I don't quite understand it.

Upvotes: 2

Views: 61

Answers (1)

user2371524
user2371524

Reputation:

culprit is probably this line:

pthread_join(p, (void**)&returnValue);

you cast a pointer to int to a pointer to void *. Let me guess, you're on amd64? void * takes 8 bytes then, while int takes 4 bytes. So you're probably overwriting your i in the same stack frame.

The right thing would be to declare void *returnValue and call it like this:

pthread_join(p, &returnValue);

Then you can for example check (int)returnValue.

Upvotes: 4

Related Questions