![](/img/trans.png)
[英]Why does start_routine for pthread_create return void* and take void*
[英]What is the type of "start_routine" passed to pthread_create
以下是在 C 中创建新线程的示例:
void *myThreadFun(void *vargp){
//
}
int main(){
pthread_t thread_id;
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
exit(0);
}
从linux man pages
我可以看到pthread_create
定义如下:
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg);
以下是我的问题:
1- start_routine
的类型是什么? 这是pointer to a function pointer
吗?
2- *myThreadFun
的类型是什么? 和上面一样吗? 指向 function 指针的指针?
2- 为什么pthread_create
不能只接收一个普通的function pointer
?
start_routine
的类型是什么? 这是指向 function 指针的指针吗?
不,这只是一个指向 function 的 [简单] 指针:
void *(*start_routine)(void *)
这是一个指向 function 的指针,它采用void *
指针作为参数,返回类型为void *
也许这会更清楚:
int (*intfunc_routine)(void *)
这里更明显的是函数/指针的返回类型是int
虽然从线程 function 的返回是一个void *
,但这更像是一个“返回码”。 通常的返回是return (void *) 0;
成功和(例如) return (void *) 1;
为错误。 这类似于main
的返回值
*myThreadFun
的类型是什么? 和上面一样吗? 指向 function 指针的指针?
再一次, myThreadFun
只是前面提到的类型的 function。 当一个人这样做时:
myThreadFun()
这是对 function 的调用。
只是在做:
myThreadFun
(不带括号)是该 function 的地址(即指向函数的指针)。
为什么
pthread_create
不能只接收一个普通的 function 指针?
正如我们现在所看到的,它确实只接收一个“正常”的 function 指针
更新:
所以你说
int (*intfunc_routine)(void *)
等于int * (*intfunc_routine)(void *)
?
不,它们不相等。 第一个是指向返回int
的 function 的指针。 第二个是指向 function 的指针,它返回指向int
的指针(即int *
)。
开头的 int 前面有一个额外的星号。 这就是 start_routine 的样子,它的开头有一个额外的星号。 – 丹
语法:
return_value_type (*func_pointer)(anyargs);
(*func_pointer)
指定指向 function 的指针。 return_value_type
可以是任何有效类型(例如void
、 int
、 char *
、 double
等)。 anyargs
是 func_pointer 指向的func_pointer
的参数列表。
考虑(例如) malloc
的前向声明。 这将在stdlib.h
中,您也可以在man malloc
中看到它:
void *malloc(size_t size);
要将其转换为 function 指针(例如):
void *(*pointer_to_malloc)(size_t size);
这是一个小程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
// pointer to function that is compatible with malloc
void *(*pointer_to_malloc)(size_t size);
void *
safe_malloc(size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr,"safe_malloc: malloc failure size=%zu -- %s\n",
size,strerror(errno));
exit(1);
}
return ptr;
}
int
main(void)
{
// we can do this ...
pointer_to_malloc = malloc;
// but we like this function better
pointer_to_malloc = safe_malloc;
// now anyone can do this ...
int *arr = pointer_to_malloc(128);
printf("main: arr=%p\n",arr);
free(arr);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.