如何将多个parameter passing给一个线程函数

我为线程创build了一个函数,但是我想传递多个参数给函数。

这是我的源代码:

#include "work.h" #include <stdio.h> #include <unistd.h> #include <pthread.h> // compile with -lpthread int count = 20; void* ChildProc(void* arg) { int i; for(i = 1; i <= count; i++) { printf("%s:%d from thread <%x>\n", arg, i, pthread_self()); DoWork(i); } return NULL; } void ParentProc(void) { int i; for(i = count / 2; i > 0; i--) { printf("Parent:%d from thread <%x>\n", i, pthread_self()); DoWork(i); } } int main(void) { pthread_t child; pthread_create(&child, NULL, ChildProc, "Child"); ParentProc(); pthread_join(child, NULL); // make child a non-daemon(foreground) thread } 

现在我如何将多个parameter passing给ChildProc()方法?

一种方法是通过数组或结构。 但是如果我想传递多个variables而没有数组或结构呢?

你可以传递一个void *缓冲流,如果你知道长度,那么你可以访问它们。 它类似于GArrays的实现。

你如何创建它们?

 void *buffer = malloc(sizeofelements); memcpy(buffer,element1,sizeof element1); memcpy(buffer+sizeof element1,element2, sizeof element2); 

注意:以上不是可编译的C代码。 你需要处理它。

你可以使用上述类型的东西。

您可以稍后访问变量,因为您已经知道这个大小

一个快速和垃圾的答案是创建一个结构来保存所有参数,并传递其指针

一种方法是通过一个数组或结构。

就是这样。 指向一个结构,也就是说。

如果我想通过一个数组或结构的多个变量呢?

那你运气不好 数组或指向结构的指针就是你所需要的。