C++多线程调用其他类函数并处理返回值问题求助
处理C++线程返回值的两种常用方法
你当前用std::thread调用类成员函数时,std::thread本身不会捕获函数的返回值,要获取返回值可以用以下两种实用方法:
方法一:使用std::async(简洁推荐)
std::async可直接异步执行函数,并返回std::future对象来获取返回值。修改main.cpp如下:
#include <stdlib.h> #include <fstream> #include <iostream> #include "vadd.h" #include <thread> #include <chrono> #include <algorithm> #include <future> // 需添加此头文件 #include "vmgr.h" using namespace std::chrono; int main(int argc, char* argv[]) { VMGR vm; // 异步调用成员函数,获取绑定返回值的future对象 std::future<int> f1 = std::async(&VMGR::helloFunction, std::ref(vm), 20); std::future<int> f2 = std::async(&VMGR::helloFunction, std::ref(vm), 30); // get()会阻塞直到线程执行完成,获取返回值 int res1 = f1.get(); int res2 = f2.get(); std::cout << "线程1返回值:" << res1 << std::endl; std::cout << "线程2返回值:" << res2 << std::endl; return 0; }
说明:
std::ref(vm)用于传递对象引用,避免创建VMGR的拷贝;若类允许拷贝,也可直接传值,但通常建议传引用/指针操作同一个对象。get()方法只能调用一次,调用后future对象会变为无效状态。
方法二:使用std::packaged_task(灵活控线程)
std::packaged_task可把函数包装成可调用对象,绑定返回值到std::future,再交给std::thread执行。修改main.cpp如下:
#include <stdlib.h> #include <fstream> #include <iostream> #include "vadd.h" #include <thread> #include <chrono> #include <algorithm> #include <future> // 需添加此头文件 #include "vmgr.h" using namespace std::chrono; int main(int argc, char* argv[]) { VMGR vm; // 包装成员函数,函数签名需匹配:int(int) std::packaged_task<int(int)> task1(std::bind(&VMGR::helloFunction, &vm, std::placeholders::_1)); std::packaged_task<int(int)> task2(std::bind(&VMGR::helloFunction, &vm, std::placeholders::_1)); // 获取用于接收返回值的future对象 std::future<int> f1 = task1.get_future(); std::future<int> f2 = task2.get_future(); // 启动线程执行包装后的任务,传入参数 std::thread t1(std::move(task1), 20); std::thread t2(std::move(task2), 30); // 等待线程执行完成 t1.join(); t2.join(); // 获取返回值 int res1 = f1.get(); int res2 = f2.get(); std::cout << "线程1返回值:" << res1 << std::endl; std::cout << "线程2返回值:" << res2 << std::endl; return 0; }
说明:
std::bind用来绑定类成员函数和对象指针,std::placeholders::_1代表占位的参数(对应helloFunction的int x)。std::packaged_task不可拷贝,需用std::move转移所有权给std::thread。
内容的提问来源于stack exchange,提问作者sarika
相关产品推荐
相关产品推荐

