c将多个参数传递给线程

时间:2012-06-22 19:08:07

标签: c multithreading pthreads posix

当我创建一个线程时,我想传递几个参数。 所以我在头文件中定义了以下内容:

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

};

在.c文件中,我执行以下操作

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

如何将所有这些参数传递给线程。我虽然关于:

1)首先使用malloc为此结构分配内存,然后为每个参数赋值:

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

2)定义

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

然后,我如何在线程中访问这些参数     void thread_function(void * arguments){     ???     }

提前致谢

4 个答案:

答案 0 :(得分:4)

这是一个有效的(相对较小的例子):

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

答案 1 :(得分:0)

不要使用选项#2。可以覆盖data结构(显式地,例如使用相同的结构来启动另一个线程,或者隐式地,例如将其覆盖在堆栈上)。使用选项#1。

要获取您的数据,请在您的主题开始时执行

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

然后正常访问info。线程完成后确保free(或者,根据我的喜好,在加入线程后让调用者释放它)。

答案 2 :(得分:0)

创建指向结构的指针,就像在上面的第一种情况中那样:

//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);

答案 3 :(得分:0)

1)你需要使用malloc而不是像下面那样定义

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

并在ptherad调用中传递结构的指针,如下所示

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

2)你可以在线程函数中访问它们,如下所示

void thread_function ( void *arguments){

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

info->....

}