c++ - 如何将函数 agruments(pointer, reference) 传递给“新线程”并期望返回值?
问题描述
我正在尝试使用线程将从类的成员函数接收到的指针传递给同一类的另一个成员函数,并期望返回值。
class tictactoe
{
...
..
.
};
class AI {
public:
int pickSpot(tictactoe* game){
t = new thread([this]() {findOptions(game);} );
return 0;
}
int findOptions(tictactoe* game){ return 0;}
};
导致错误:错误:无法在未指定捕获默认值的 lambda 中隐式捕获变量“游戏”
它是怎么做的?
解决方案
要获得返回值,您可以使用 std::future 和 std::async:
#include <future>
#include <thread>
int pickSpot(tictactoe* game){
std::future<int> f = std::async(std::launch::async, [this, game]() { return findOptions(game); });
f.wait();
int res = f.get();
return res;
}
推荐阅读
- spring-boot - 嵌入式数据库错误:为什么它给出空结果
- nuxt.js - Nuxt 多个资产发射到相同的文件名热更新
- python - 使用pyquaternion旋转向量数组
- php - 如何使用 ajax 将数据属性发送到 laravel 控制器(存储在数据库中)?
- excel - IE关闭窗口并在新窗口中连接定向链接
- java - 如何为每个 recyclerview 项目的按钮添加功能?
- sql - 列出 sql server 中包含特定列的所有对象
- azure - 填充选项列表时如何在 Extension task.json 中对数据源绑定进行排序和过滤
- java - Spring Boot:@PreAuthorize 给出 403 禁止 AccessDeniedException
- php - Codeigniter XML-RPC 连接到 Odoo 域错误