multithreading - Make Monte Carlo eval multithreaded for Hexgame C++ -
i trying make monte carlo eval function multithreaded computer player in hexgame faster. normal code (without multithreading) is:
using namespace std; int getmontecarloeval(const state &board, player player, int trials) { vector<move> moves = board.getmoves(); int wins = 0; (int = 0; < trials; ++i) { state mcboard = board; random_shuffle(moves.begin(), moves.end()); (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; }
with multithreading have this:
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; (int = 0; < nr_threads; i++) { r = l + delta; if (i == nr_threads - 1) r += remainder; workers.push_back(thread(mc, mcboard, player, l, r)); l = r; } (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) { (int = l; < r; i++) { state mcboard = board; random_shuffle(moves.begin(), moves.end()); (move m : moves) mcboard.domove(m); if (mcboard.getwinner() == player) wins++; } }
the problem here is, computer player freaking stupid. without multithreading computer player plays slow. use alpha berta pruning searching best next step computer.
question: know doing wrong multithreading?
Comments
Post a Comment