void指针函数的用法

Usage of void pointer function

本文关键字:用法 函数 指针 void      更新时间:2023-10-16

我一直在研究以下工作代码,以便在c++中作为pthread执行代码:

void * PrintHello(void * blank) { 
    cout << "Hello World" << endl
}
...
pthread_create(&mpthread, NULL, PrintHello, NULL);

我想知道为什么我需要使用void*方法而不是void方法,参数也是如此。为什么它们需要成为指针,在这种无效方法和无效论证的情况下有什么区别。

您需要使用一个接受void*的方法,因为它是由pthread库调用的,而pthread库会向您的方法传递void*——与您将pthread_create作为最后一个参数传递的指针相同。

以下是如何使用单个void*:将任意参数传递给线程的示例

struct my_args {
    char *name;
    int times;
};
struct my_ret {
    int len;
    int count;
};
void * PrintHello(void *arg) { 
    my_args *a = (my_args*)arg;
    for (int i = 0 ; i != a->times ; i++) {
        cout << "Hello " << a->name << endl;
    }
    my_ret *ret = new my_ret;
    ret->len = strlen(a->name);
    ret->count = strlen(a->name) * a->times;
    // If the start_routine returns, the effect is as if there was
    // an implicit call to pthread_exit() using the return value
    // of start_routine as the exit status:
    return ret;
}
...
my_args a = {"Peter", 5};
pthread_create(&mpthread, NULL, PrintHello, &a);
...
void *res;
pthread_join(mpthread, &res);
my_ret *ret = (my_ret*)(*res);
cout << ret->len << " " << ret->count << endl;
delete ret;

尽管您的函数不想接受任何参数或返回任何内容,但由于pthread库向其传递参数并收集其返回值,因此您的函数需要具有适当的签名。将指针传递给不带参数的void函数而不是带一个参数的void*函数将是未定义的行为。