我正在努力使我的蒙特卡罗评估功能成为多线程,因此我的hexgame中的计算机播放器会更快。普通代码(没有多线程)是:
using namespace std;
int getMonteCarloEval(const State &board, Player player, int trials)
{
vector<Move> moves = board.getMoves();
int wins = 0;
for (int i = 0; i < trials; ++i)
{
State mcBoard = board;
random_shuffle(moves.begin(), moves.end());
for (const Move &m : moves)
mcBoard.doMove(m);
if (mcBoard.getWinner() == player)
wins++;
}
return wins - trials / 2;
}
int getRandomEval(const State &board, Player)
{
return rand() % 101 - 50;
}
使用多线程我有这个:
using namespace std;
vector<Move> moves;
atomic<int> wins = 0;
int getMonteCarloEval(const State &board, Player player, int trials)
{
vector<Move> moves = board.getMoves();
State mcBoard = board;
size_t nr_threads = 8;
vector<thread> workers;
int delta = trials / nr_threads;
int remainder = trials % nr_threads;
int L = 0; int R = 0;
for (int i = 0; i < nr_threads; i++) {
R = L + delta;
if (i == nr_threads - 1)
R += remainder;
workers.push_back(thread(mc, mcBoard, player, L, R));
L = R;
}
for (auto &thread : workers) {
thread.join();
}
return wins - trials / 2;
}
int getRandomEval(const State &board, Player)
{
return rand() % 101 - 50;
}
int mc(const State &board, Player player, int L, int R)
{
for (int i = L; i < R; i++)
{
State mcBoard = board;
random_shuffle(moves.begin(), moves.end());
for (Move m : moves)
mcBoard.doMove(m);
if (mcBoard.getWinner() == player)
wins++;
}
}
这里的问题是,现在的计算机播放器确实非常愚蠢。如果没有多线程,计算机播放器的播放速度非常慢。 我还使用Alpha Berta修剪来搜索计算机的最佳下一步。
问题:有人知道我在使用MultiThreading时遇到了什么问题吗?