c++ - pthread返回值错误

标签 c++

我是 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/

相关文章:

c++ - 嵌套类型 : struct vs class

C++ 不会退出 do while 循环

C++:具有相同要求的此范围 View 构造的替代方案?

c++ - Floyd 算法使用 (const vector<int>& t : flights), 存储在 't' 上的值是什么

c++ - std::cin 适用于少量行,但不适用于较大行

c++ - DisplayImage.cpp 错误 将 OpenCV 与 gcc 和 CMake 结合使用

c++ - 访问整个数组的顺序程序

c++ - 如何逐行读取文件或一次读取整个文本文件?

C++ exp LUT(查找表)

c++ - 指向记录器类的指针提供给所有其他类?