![](/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.