سؤال

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void * function(void *);

main()
{
  pthread_t p[5];
  int j;
  int *arg1[4];
  int arr[5]={1,2,3,4,5};
  for(j=0;j<=4;j++) 
    pthread_create(&p[j],NULL,function,&arr[j]);
  for(j=0;j<=4;j++)
    pthread_join(p[j],(void **)&arg1[j]);
  for(j=0;j<=4;j++)
    printf("\n%d",*arg1[j]);

}

void * function(void *arg)
{
 int *i = (int *) arg;
 pthread_exit(i);
}

Output:
-1498551536
32767
3
4
5

Q.1) It is always printing junk values for first two values. Why is it so? please correct me if anything is wrong here.

When i changed the code like below, it is properly printing 1,2,3,4,5.

  for(j=0;j<=4;j++)
  { 
    pthread_join(p[j],(void **)&arg1[j]);
    printf("\n%d",*arg1[j]);
  }

Q.2) what are the different methods of returning values from thread? Can you please summarize all the methods with example and explain which one is the method to follow?

هل كانت مفيدة؟

المحلول

your arg1 is only size 4, but you're filling 5. Setting it to the proper size will fix your problem.

In your example that doesn't work, you're not printing until you pthread_join all the threads before you print them. You get corruption before you print when you join the fifth thread.

In your example that works, printing each result before joining to the next thread. This means you print before the fifth thread overwrites the first and second values (they are still being overwritten).

The reason it's the first two that are corrupted is because your ints are probably 32-bit and your pointers are probably 64-bit. So 1 extra pointer messes up the next two int positions.

As for returning complex results from a thread, pthread_exit returns a void * and pthread_join gets the value as an output parameter when it returns.

pthread_join

pthread_exit

So if you need to return more than a primitive value, then put together a struct and return that.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top