简体   繁体   English

Pthread,与pthread_join(pthread_t,void **)混淆

[英]Pthreads, confusion with pthread_join(pthread_t, void**)

我不明白为什么pthread_join将第二个参数void**作为返回值,而给定返回值的pthread_exit将返回值参数作为void*

pthread_join waits for the thread to end, and the resulting value from pthread_exit is stored into *value_ptr. pthread_join等待线程结束,并将pthread_exit的结果值存储到* value_ptr中。 If you want to ignore the result, you can pass NULL for the value_ptr. 如果要忽略结果,则可以将NULL传递给value_ptr。 This is the common C practice of simulating pass by reference by passing a pointer to a variable. 这是通过将指针传递给变量来模拟按引用传递的通用C惯例。 See Passing by reference in C 请参见在C中通过引用传递

The pthread_join returns 0 as the function return value on success; pthread_join成功时返回0作为函数返回值;否则返回0。 then you know that the thread has been joined, and you can access the value from *value_ptr. 那么您就知道该线程已加入,您可以从* value_ptr中访问该值。

void *value = NULL;
if (pthread_join(thread, &value) == 0) {
    // thread has ended, and the exit value is available in
    // the value variable
} 

Essentially, pthread_join() wants to return two peices of information: 本质上, pthread_join()要返回两个信息:

  • a success/failure indication 成功/失败指示
  • whatever the thread returned (which has a type void* ) 返回的任何线程(类型为void*

In C, the typical way a function 'returns' two separate values is to have the function return one of those values normally and to 'return' the ofther value in a location provided by the caller where the caller passes in a pointer to that location. 在C语言中,函数“返回”两个单独值的典型方式是使函数正常返回这些值之一,并在调用者提供的位置(调用者将指针传递到该位置)中“返回”另一个值。 。 So pthread_join() : 所以pthread_join()

  • returns success/failure as the function's value 返回成功/失败作为函数的值
  • returns the thread's void* result in a caller-provided location that the caller passes a void** to. 返回线程的void*导致调用者将void**传递给调用者提供的位置。

Note that in pthread_join() 's case, the caller-provided location is optional. 请注意,在pthread_join()的情况下,调用方提供的位置是可选的。 NULL can be passed in id the caller isn't interested in that result. 可以在呼叫者对该结果不感兴趣的id中传递NULL。 Making the caller-provided location optional is a common, by by no means universal, idiom. 将呼叫者提供的位置设置为可选是很普遍的,绝不是通用的。

pthread_exit() doesn't need to use a void** as it's argument because that argument isn't a result of the function. pthread_exit()不需要使用void**作为参数,因为该参数不是函数的结果 So it can simply take the value directly. 因此,它可以直接直接取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM