0
votes

I am trying to create five threads in the main thread.

In the pthread_create() function, I am passing increasing 'num' value as a variable to function 'up' each time, so I thought the value of y in each thread should be 1,2,3,4 and 5 in a random order, respectively.

However, when printf("before add num is %d\n", y) in function 'up' is called which is to check the value of y , it shows y could be undetermined which means y may be any number between 1 to 5.

How shall I fix this parallel input problem...Thanks in advance for any help!

const int TOTAL_RUNS = 1000000;

void *up(void *ptr) { 
  int i;
  int y = *((int*)ptr);
  printf("before add num is %d\n", y);

  for (i = 0; i < TOTAL_RUNS; i++)
    y++;

  printf("Finished adding 1 a total of %d times.\n", TOTAL_RUNS);
}

void main() {
  int num = 1;
  pthread_t t[5];
  int i;

  for (i = 0; i < 5; i++) {
    pthread_create(&t[i], NULL, up,(void*) &num);
    num++;
  }

  for (i = 0; i < 5; i++) {
    pthread_join(t[i], NULL);
  }
}
1

1 Answers

3
votes

The problem is you're passing the same address to every thread - each thread has access to the same memory location (since you passed &num to each of them).

The cheapest way you could fix this would be to use an array:

int nums[] = {1, 2, 3, 4, 5};
/* ... */

pthread_create(&t[i], NULL, up, &nums[i]);

That should be safe since you call join in the same thread (nums won't go out of scope before the threads are done).