Search code examples
cmultithreadingpthreadsposix

c passing several arguments to threads


when i create a thread, i want to pass several arguments. So i define in a header file the following:

struct data{
  char *palabra;
  char *directorio;
  FILE *fd;
  DIR *diro;
  struct dirent *strdir;

};

In a .c file i do the following

if (pthread_create ( &thread_id[i], NULL, &hilos_hijos, ??? ) != 0){
       perror("Error al crear el hilo. \n");
       exit(EXIT_FAILURE);
} 

How do i pass all this arguments to the threads. I though about:

1) first use malloc to allocate memory for this structure and then give each parameter a value:

 struct data *info
 info = malloc(sizeof(struct data));
 info->palabra = ...;

2) define

 struct data info 
 info.palabra = ... ; 
 info.directorio = ...; 

and then, how do i access these parameters in the thread void thread_function ( void *arguments){ ??? }

thanks in advance


Solution

  • Here is a working (and relatively small) example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <pthread.h>
    
    /*                                                                                                                                  
     * To compile:                                                                                                                      
     *     cc thread.c -o thread-test -lpthread                                                                                         
     */
    
    struct info {
        char first_name[64];
        char last_name[64];
    };
    
    void *thread_worker(void *data)
    {
        int i;
        struct info *info = data;
    
        for (i = 0; i < 100; i++) {
            printf("Hello, %s %s!\n", info->first_name, info->last_name);
        }
    }
    
    int main(int argc, char **argv)
    {
        pthread_t thread_id;
        struct info *info = malloc(sizeof(struct info));
    
        strcpy(info->first_name, "Sean");
        strcpy(info->last_name, "Bright");
    
        if (pthread_create(&thread_id, NULL, thread_worker, info)) {
            fprintf(stderr, "No threads for you.\n");
            return 1;
        }
    
        pthread_join(thread_id, NULL);
    
        return 0;
    }