提问人:artic sol 提问时间:11/10/2017 最后编辑:alkartic sol 更新时间:10/27/2023 访问量:5745
为什么 pthread_join() 的第二个参数是 **,指向指针的指针?
Why the second argument to pthread_join() is a **, a pointer to a pointer?
问:
我是使用新手,也不熟悉指针到指针。有人可以解释为什么第二个参数是.为什么是这样设计的。pthread
pthread_join()
void **
int pthread_join(pthread_t thread, void **value_ptr);
答:
12赞
alk
11/11/2017
#1
要通过函数的参数返回值,您需要传入变量的地址以接收新值。
由于 pthread_join(
) 旨在接收传递给 pthread_exit(
) 的指针值,因此 pthread_join()
需要 的地址,而该地址实际上是 类型的 。void*
void*
void**
例:
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for printf() and perror() */
#include <pthread.h>
void * tf(void * pv)
{
int * a = pv;
size_t index = 0;
printf("tf(): a[%zu] = %d\n", index , a[index]);
++index;
pthread_exit(a + index); /* Return from tf() the address of a's 2nd element.
a + 1 here is equivalent to &a[1]. */
}
int main(void)
{
int a[2] = {42, 43};
pthread_t pt;
int result = pthread_create(&pt, NULL, tf, a); /* Pass to tf() the address of
a's 1st element. a decays to
something equivalent to &a[0]. */
if (0 != result)
{
perror("pthread_create() failed");
exit(EXIT_FAILURE);
}
{
int * pi;
size_t index = 0;
{
void * pv;
result = pthread_join(pt, &pv); /* Pass in the address of a pointer-variable
pointing to where the value passed to
pthread_exit() should be written. */
if (0 != result)
{
perror("pthread_join() failed");
exit(EXIT_FAILURE);
}
pi = pv;
}
++index;
printf("main(): a[%zu] = %d\n", index, pi[0]);
}
return EXIT_SUCCESS;
}
上面的程序预计会打印:
tf(): a[0] = 42
main(): a[1] = 43
0赞
ArgyrisSofroniou
10/27/2023
#2
基本上,pthread_join() 通过其 void **value_ptr 链接 void *joinPointer 和 void *exitPointer;
// void *joinPointer; (the pointer you gave to pthread_join)
// void *exitPointer; (the pointer you gave to pthread_exit)
void pthread_exit(void *retval);
int pthread_join(pthread_t thread, void **value_ptr){
...
*value_ptr = <retval>; //retval points to what exitPointer pointed to
...
}
int main(){
...
void *joinPointer;
...
pthread_join(ithread, &joinPointer)
...
}
评论
pthread_exit(void* retval);
pthread_join()