c 将多个参数传递给线程

标签 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){ ???

提前致谢

最佳答案

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

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

关于c 将多个参数传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11162613/

相关文章:

c - 如何在不使用互斥量、futex 和信号量的情况下实现 "locking"机制?

c - 如何在 Linux 平台上的不同线程之间用 C 创建阻塞队列

C - 对结构指针数组进行排序比直接对结构进行排序 (qsort)

创建一个仅包含旧字符串中的字母数字字符的新字符串

c - 从数组中读取两个 int 作为 long

c - 输出正确,但在 c 中显示运行时错误

c# - 从后台线程通知 UI 线程

java - 同步代码块

在 for 循环中创建 C pthread 结构体

c# - 启动多进程并异步重定向输出