I just started learning multi-threading in C++ with pthreads. I am working with the following code:
struct ArgT{
int a;
int b;
ArgT(int a, int b)
: a(a), b(b)
{}
ArgT()
:a(0), b(0)
{}
};
void* worker(void* arg)
{
ArgT* myArg = (ArgT*) arg;
int* result = new int;
*result = myArg->a + myArg->b;
std::cout << "(void*)result: " << (void*) result << std::endl;
return (void*)result;
}
int main()
{
ArgT mainArg(2,3);
pthread_t p;
int* main_result;
pthread_create(&p, NULL, worker, (void*)&mainArg);
pthread_join(p, (void**)&main_result); //??
std::cout << "main_result: " << main_result << std::endl;
std::cout << "&main_result: "<< &main_result << std::endl;
printf("\nResult = %d\n", *main_result);
delete main_result;
return 0;
}
The output of the code is as follows
(void*)result: 0x7f07ac0008c0
main_result: 0x7f07ac0008c0
&main_result: 0x7fffb1aa0588
Result = 5
My question is pthread_join()
accepts void**
as second argument, which is basically address of an address. Whereas we are returning an address of type void*
in the worker()
function. How are these two types compatible?
pthread_join()
takes the address of a pointer variable. That variable will receive the pointer value that the thread returns. It is effectively doing the same as this: