c++ - 如何在C++中异步调用静态方法?

标签 c++ multithreading asynchronous future

我想异步运行我的极小极大算法,这样它就不会在等待转弯时卡住用户界面。这是我需要调用的静态方法:

//ChessContext is the current state of the board
//Turn contains fromX, fromY, toX, toY when moving a piece
static Turn getBestTurn(ChessContext cc, int depth);

我已经尝试过这个:

//context is a reference to the game currently played
auto fu = std::async(std::launch::async, ChessContext::getBestTurn, context , 5);
Turn t = fu.get();

它给我一个错误说

boardview.cpp:69:23: error: no matching function for call to 'async' 
future:1712:5: note: candidate template ignored: substitution failure [with _Fn = Turn (&)(ChessContext, int), _Args = <ChessContext &, int>]:
    no type named 'type' in 'std::result_of<Turn ((ChessContext, int))(ChessContext, int)>'
future:1745:5: note: candidate template ignored: substitution failure [with _Fn = std::launch, _Args = <Turn (&)(ChessContext, int), ChessContext &, int>]:
    no type named 'type' in 'std::result_of<std::launch (Turn ()(ChessContext, int), ChessContext, int)>'

我最终希望在单独的线程上的每个可能的回合上运行该算法,或者一次在两个线程上运行该算法,看看它是否可以提高性能。

最少代码:

#include <iostream>
#include <thread>
#include <future> 

class Turn
{
};
class ChessContext 
{
public:
    ChessContext();
    ChessContext(ChessContext &cc);

    static Turn getBestTurn(ChessContext cc, int depth);
}; 

int main(){
    ChessContext context;
    auto fu = std::async(std::launch::async, ChessContext::getBestTurn, context, 5);
}

这是完整的项目 https://github.com/zlatkovnik/Super-Chesster.git

最佳答案

ChessContext 不可复制。 ChessContext(ChessContext &cc) 不是复制构造函数,您需要 ChessContext(const ChessContext &cc)

关于c++ - 如何在C++中异步调用静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59800741/

相关文章:

c++ - 移动仅由另一个成员函数使用的成员函数并使它们成为本地函数时的性能考虑?

c++ - 有没有办法让这些密切相关的类型可以互操作?

java - 2 个 JVM 之间的低 CPU 使用率轮询架构

php - 在浏览其他页面时上传多个文件 - 如何?

loops - Coldfusion - 数据库记录更新时刷新页面

c++ - 关于函数指针 : why the overhead time changes when the content of the function changes

multithreading - 无状态 session 线程安全吗?

java - 当程序的状态不断变化时,不可变对象(immutable对象)的用处

java - 在鼠标按下事件中启动 "asyncExec"会导致阻塞行为

c++ - 从命令行创建通用对象