温馨提示×

c++ pthread怎么获取线程返回值

c++
小樊
83
2024-06-25 16:37:29
栏目: 编程语言

在C++中使用pthread库创建线程时,线程没有返回值的概念。通常情况下,可以通过将返回值存储在一个共享的变量中来实现线程返回值的获取。

以下是一种实现方式:

  1. 在创建线程时,将一个指向共享变量的指针传递给线程函数作为参数。

  2. 在线程函数中,将计算得到的返回值存储在共享变量中。

  3. 在主线程中,等待线程结束后,从共享变量中获取返回值。

下面是一个简单的示例代码:

#include <iostream>
#include <pthread.h>

// 共享变量
int result;

// 线程函数
void* threadFunc(void* arg) {
    int* presult = static_cast<int*>(arg);
    
    // 计算返回值
    *presult = 42;
    
    pthread_exit(NULL);
}

int main() {
    pthread_t tid;
    
    // 创建线程,传递共享变量result的地址作为参数
    pthread_create(&tid, NULL, threadFunc, &result);
    
    // 等待线程结束
    pthread_join(tid, NULL);
    
    // 输出返回值
    std::cout << "Thread returned: " << result << std::endl;
    
    return 0;
}

在这个示例中,线程函数threadFunc计算了返回值42,并将其存储在共享变量result中。在主线程中,使用pthread_join函数等待线程结束后,从result中获取返回值并输出。

0