如何将多个参数传递给线程函数

时间:2010-09-09 05:50:00

标签: c unix ubuntu posix

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

这是我的源代码:

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

现在如何将多个参数传递给ChildProc()方法?

一种方法是传递数组或结构。但是如果我想在没有数组或结构的情况下传递多个变量呢?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:3)

  

一种方法是传递数组或结构。

那是 方式。 指针到一个结构,即。

  

如果我想传递带有数组或结构的多个变量怎么办?

然后你运气不好。您需要的是数组或指向结构的指针。

答案 2 :(得分:1)

您可以传递void *缓冲区流,如果您知道长度,则可以访问它们。它类似于GArrays的实现。

你如何创造它们?

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

注意:上述内容不是可编译的C代码。你需要努力。

您可以使用上述类别的内容。

您可以稍后访问已知大小的变量

相关问题