c passing several arguments to threads

前端 未结 4 443
暗喜
暗喜 2021-01-14 21:21

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;
  FI         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-14 21:35

    Here is a working (and relatively small) example:

    #include 
    #include 
    #include 
    #include 
    
    /*                                                                                                                                  
     * 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;
    }
    

提交回复
热议问题