pthread return value error
I am new to Linux programming.
I am returning a value from thread. But when compiled it is listing some errors. I am listing the code and error below. Please help me to understand why the error and how to solve it.
code
#include <pthread.h>
#include <stdio.h>
void* compute_prime (void* arg)
{
int x = 2;
return (void*) x;
}
int main ()
{
pthread_t thread;
int prime;
pthread_create (&thread, 开发者_开发百科NULL, &compute_prime, NULL);
pthread_join (thread, (void*) &prime);
printf("The returned value is %d.\n", prime);
return 0;
}
error
$ g++ -othj pdfex.cpp -lpthread
pdfex.cpp: In function `int main()':
pdfex.cpp:17: error: invalid conversion from `void*' to `void**'
pdfex.cpp:17: error: initializing argument 2 of `int pthread_join(pthread_t, void**)'
What am I doing wrong?
Since the declaration of pthread_join()
is:
int pthread_join(pthread_t thread, void **value_ptr);
your '(void *)
' cast is wrong - and the compiler is telling you that.
How to fix?
If
sizeof(void *) == sizeof(int)
on your machine, then:pthread_join(thread, (void **)&prime);
Otherwise:
uintptr_t uip; pthread_join(thread, (void **)&uip); prime = uip;
That requires
#include <stdint.h>
(or#include <inttypes.h>
), and exploits the fact that auintptr_t
is the same size as avoid *
.
This code delivers the answer 2 when compiled for 64-bit on MacOS X 10.6.4 (which corresponds to the 'otherwise' clause):
#include <pthread.h>
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>
static void *compute_prime(void* arg)
{
uintptr_t x = 2;
assert(arg == 0);
return (void *)x;
}
int main(void)
{
pthread_t thread;
uintptr_t prime;
pthread_create(&thread, NULL, &compute_prime, NULL);
pthread_join(thread, (void **) &prime);
printf("The returned value is %" PRIuPTR ".\n", prime);
return 0;
}
pthread_join() is asking for a void**
, and you are giving it a void*
.
精彩评论