【问题标题】:Usage of void pointer function [duplicate]void指针函数的使用[重复]
【发布时间】:2013-05-24 09:12:38
【问题描述】:

我一直在查看以下工作代码,用于在 c++ 中将代码作为 pthread 执行:

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

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

【问题讨论】:

  • 您在这里没有使用任何类型的方法。 C 没有方法。
  • @H2CO3 方法,功能,笨拙,只是同一事物的不同名称。
  • @DanielFischer 在 OOP 中“方法”没有命名“成员函数”吗? (据我所知,甚至 C++ 标准都没有使用术语方法,而是成员函数。)
  • @H2CO3 我们不受 OOP 术语的约束,这也不是很统一。 Javans 过去(也许仍然如此)将所有函数称为“方法”,有些是“实例方法”,有些是“类方法”。至少在一开始,虔诚地避免使用“函数”一词的部分原因是感觉 OOP 在本质上优于老式的过程式编程(恐怕 OOP 还没有失去足够的新鲜感来彻底摧毁这种信念,对某些任务更好,对另一些任务更糟)。不会改变它们都是函数的事实。
  • @H2CO3 不用担心,你听起来不像。我只是强烈认为坚持术语不同是毫无意义的,除非相关标准中有规定。

标签: c++ pointers pthreads


【解决方案1】:

您需要使用采用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* 函数将是未定义的行为。

【讨论】:

  • 为什么返回类型是void*
  • @PeterWood 这样你的线程也可以将数据返回给调用者(通过pthread_join)。
  • 是的,这就是我认为的主要问题。
  • 好的,所以 void* 被用作通用指针,这样任何争论都可以通过 pthread_create 传入。如果我不想返回任何东西,我仍然不明白为什么将 void * 用作返回类型。如果我从这个方法返回一个 int,我将如何使用返回值?
  • @NickHorne 查看更新后的示例,并解释为什么您需要 arg 和返回类型,即使您不打算使用它们中的任何一个。
猜你喜欢
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
  • 2016-11-23
  • 2012-09-09
  • 2013-05-21
  • 2020-06-11
相关资源
最近更新 更多