如何将多个参数传递给线程函数 [英] How to pass multiple parameters to a thread function

查看:196
本文介绍了如何将多个参数传递给线程函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个线程的功能,但我想多个参数传递给函数。

I have created a function for a thread, but I want to pass multiple parameters to the function.

下面是我的源$ C ​​$ C:

Here's my source code :

#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()方法?

Now how do I pass multiple parameter to ChildProc() method?

的一种方式是要么通过阵列或结构。但是,如果我想要传递多个变量,而一个数组或结构?

One way is either pass an array or a structure. But what if I want to pass multiple variables without an array or a structure?

推荐答案

您可以通过一个无效* 缓冲流,如果你知道的长度,那么你可以访问它们。它类似于实施 GArrays

You can pass a void * buffer stream and if you know the lengths then you can access them. Its similar to implementation of GArrays.

如何创建呢?

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

注意:以上是不是编译C $ C $℃。您需要进行这项工作。

NOTE: The above is not a compilable C code. You need to work on it.

您可以用上面的诸如此类的东西。

You can use something of the above sort.

您可以稍后访问的变量,你已经知道了大小

You can later access the variables as you already know the size

这篇关于如何将多个参数传递给线程函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆