如何将函数agruments指针,引用传递给“新线程”并期望返回值?

问题描述

我正在尝试使用线程将从类的成员函数收到的指针传递给同一类的另一个成员函数,并期望返回值。

    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:

import CPromise from "c-promise2"; // npm package

function fetchWithTimeout(url,{timeout,...fetchOptions}= {}) {
    return new CPromise((resolve,reject,{signal}) => {
        fetch(url,{...fetchOptions,signal}).then(resolve,reject)
    },timeout)
}
        
const chain = fetchWithTimeout("https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=10s",{timeout: 5000})
    .then(request=> console.log('done'));
    
// chain.cancel(); - to abort the request before the timeout