首页 > 解决方案 > 如何将函数 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 中隐式捕获变量“游戏”

它是怎么做的?

标签: c++multithreadingfunctionreturnpthreads

解决方案


要获得返回值,您可以使用 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;
}

推荐阅读