pthreads - Pthread_join & Pthread_exit in c -


#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) printing junk values first 2 values. why so? please correct me if wrong here.

when changed code below, 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) different methods of returning values thread? can please summarize methods example , explain 1 method follow?

your arg1 size 4, you're filling 5. setting proper size fix problem.

in example doesn't work, you're not printing until pthread_join threads before print them. corruption before print when join fifth thread.

in example works, printing each result before joining next thread. means print before fifth thread overwrites first , second values (they still being overwritten).

the reason it's first 2 corrupted because ints 32-bit , pointers 64-bit. 1 pointer messes next 2 int positions.

as returning complex results thread, pthread_exit returns void * , pthread_join gets value output parameter when returns.

pthread_join

pthread_exit

so if need return more primitive value, put struct , return that.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -