void指针函数的用法
Usage of void pointer function
我一直在研究以下工作代码,以便在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*
函数将是未定义的行为。
相关文章:
- 构造函数的用法
- C++ 中函数中 Const 用法之间的差异
- 错误:使用复制和交换习惯用法的交换函数中"operator="的重载不明确
- 未命名的函数参数用法
- 使用指针复制构造函数用法
- CPP/C 中的常量用法和结构构造函数中的澄清
- 向下转换指向成员函数的指针.这是合法用法吗?
- 将 PIMPL 习惯用法与成员函数模板一起使用(无需预先了解所有可能的数据类型)
- 复制构造函数方法的用法
- C++向量用法错误:没有匹配的成员函数来调用"push_back"
- Constexpr静态成员函数用法
- 函数原型范围的有趣用法
- lambda 中的跨平台"auto"关键字用法:integral_constant作为函数参数
- 参数和成员变量在构造函数中的用法
- C 中的构造函数和破坏者的内联用法
- unique_ptr旧函数的用法
- 函数调用中“&”的用法,令人困惑
- 使用复制和交换习惯用法,复制对象的析构函数如何不解除分配指向内存
- 如何嵌入实时单元测试函数的主体作为 Doxygen 的示例用法
- C++析构函数删除包含动态数组作为数据成员的对象时的用法