c passing several arguments to threads

徘徊边缘 提交于 2019-12-01 14:33:48

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

Do not use option #2. The data structure could be overwritten (explicitly, for instance using the same structure to start another thread, or implicitly, for instance having it overwritten on the stack). Use option #1.

To get at your data, at the start of your thread, do

struct data *info = (struct data*)arguments;

Then access info as normal. Make sure to free it when the thread is done (or, as I prefer, have the caller free it after joining with the thread).

Create a pointer to a struct like you do in the first case above:

//create a pointer to a struct of type data and allocate memory to it
struct data *info
info = malloc(sizeof(struct data));

//set its fields
info->palabra   = ...;
info->directoro = ...;

//call pthread_create casting the struct to a `void *`
pthread_create ( &thread_id[i], NULL, &hilos_hijos, (void *)data);

1) you need to use malloc and not define like below

struct data *info;
info = (struct data *)malloc(sizeof(struct data));

and pass the pointer of the structure in ptherad call as below

pthread_create ( &thread_id[i], NULL, &thread_fn, (void *)info );

2) you can access them in thread function as below

void thread_function ( void *arguments){

struct data *info = (struct data *)arguments;

info->....

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!