Passing arguments to thread in C

Hi,

Im trying to figure out how to successfully pass a struct as an argument to a thread.
But i can't seem to get it right. Ideas?

Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
    
/* Prototypes */
void *run(void *thread_arg);



struct thread_args {
       
      int arraylength;
      int *ptr;
      char *name;
};
        
int main() {
        
  pthread_t thread_id;
  struct thread_args  pthread_data;
  struct thread_args *thread_data = &pthread_data;
   
    
  thread_data->arraylength = 10;
 
  strcpy(thread_data->name,"David");
  
  pthread_create(&thread_id,NULL,run,(void *)&thread_data);
  pthread_join(thread_id,NULL);
  pthread_exit(NULL);
  return 0;
  }    
       

       
 void *run(void *thread_arg) {
        
        struct thread_args *my_data;
        my_data = (struct thread_args *)thread_arg;
        printf("%s",my_data->name);   //Supposed to print "David"
         
}
 
Business_Woman said:
Hi,

Im trying to figure out how to successfully pass a struct as an argument to a thread.
But i can't seem to get it right.
Actually, you do - more or less. The error is somewhere else. Read on.

Code:
struct thread_args  pthread_data;
struct thread_args *thread_data = &pthread_data;
Although not incorrect, I find this ugly. Why declare a seperate pointer thread_data when you can simply use &pthread_data? See the next point...
Code:
pthread_create(&thread_id,NULL,run,(void *)[red]&[/red]thread_data);
Ditch the ampersand (or just write &pthread_data in the first place), thread_data is already a pointer and you're passing a pointer to that pointer but in run() you cast it back to the pointer itself.

Code:
strcpy(thread_data->name,"David");
But this is your actual mistake. Can you tell why? (hint: think memory allocation)

Hope this helps,

Fonz
 
fonz said:
Actually, you do - more or less. The error is somewhere else. Read on.

Code:
strcpy(thread_data->name,"David");
But this is your actual mistake. Can you tell why? (hint: think memory allocation)

Hope this helps,

Fonz

Hm, you have to malloc some memory for the pointer to point to?
 
Simply changing to:

Code:
thread_data->name = "David";

Will do the trick. (In current context)


Edit:

By the way, you should call pthread_exit() in your children threads and not in main().
 
Back
Top