我是 Linux 编程新手。
我正在从线程返回一个值。但是在编译时它列出了一些错误。我在下面列出了代码和错误。请帮助我理解错误的原因以及解决方法。
代码
#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;
}
错误
$ 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**)'
我做错了什么?
最佳答案
自pthread_join()
申报以来是:
int pthread_join(pthread_t thread, void **value_ptr);
你的 ' (void *)
' cast 是错误的 - 编译器会告诉您这一点。
如何修复?
如果
sizeof(void *) == sizeof(int)
在你的机器上,然后:pthread_join(thread, (void **)&prime);
否则:
uintptr_t uip; pthread_join(thread, (void **)&uip); prime = uip;
这需要
#include <stdint.h>
(或#include <inttypes.h>
),并利用uintptr_t
的事实与void *
大小相同.
此代码在 MacOS X 10.6.4 上针对 64 位编译时提供答案 2(对应于“otherwise”子句):
#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;
}
关于c++ - pthread返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3921468/