pthread with unique struct as parameter C

Posted by sergiobuj on Stack Overflow See other posts from Stack Overflow or by sergiobuj
Published on 2010-04-05T01:45:11Z Indexed on 2010/04/05 1:53 UTC
Read the original article Hit count: 332

Filed under:
|
|
|

Hi, i have this piece of code that is giving me trouble. I know all the threads are reading the same struct. But i have no idea how to fix this.

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

typedef struct {
  int a,b;
} s_param;

void *
threadfunc(void *parm)
{
  s_param *param2 = parm; 
  printf("ID:%d and v:%d\n",param2->a,param2->b);
  pthread_exit(NULL);
}

int main(int argc, char **argv)
{
  pthread_t thread[3];
  int rc=0,i;
  void * status;

  for(i=0; i<3 ; ++i){
    s_param param;
    param.b=10;
    param.a=i;
    rc = pthread_create(&thread[i], NULL, threadfunc, &param ); // !!!!
    if(rc){
      exit(1);
    }
  }  

  for(i=0; i<3 ; ++i){
    pthread_join(thread[i],&status);
  }
  return 0;
}

output:

ID:2 and v:10
ID:2 and v:10
ID:2 and v:10

and what i need:

ID:0 and v:10
ID:1 and v:10
ID:2 and v:10

Thank you.

© Stack Overflow or respective owner

Related posts about pthreads

Related posts about c