Search code examples
cmultithreadingchess

Implementing multi-threading in an already existing chess engine in C


I want to know if its possible to modify an existing chess engine in C that works without multi-threading to be able to support multi-threading. I have no experience in this subject and would appreciate some guidance.

EDIT: To be more specific, is there anything I can add to my implementation of negamax to make it multi-thread compatible? :

static double alphaBetaMax(double alpha, double beta, int depthleft, game_t game, bool player)
{
    move_t *cur;
    move_t *tmp;
    double score = 0;
    bool did_move = false;

    cur = getAllMoves(game, player);
    if(cur == NULL) /*/ check mate*/
        return -9999999*(player*2-1);
    tmp = firstMove;
    firstMove = 0;

    while (cur != NULL)
    {
        game_t copy;
        if(depthleft<=0 && !isCapture(game, cur)) { /* Quiescence search */
            cur = cur->next;
            continue;
        }
        did_move = true;
        copyGame(game, &copy);
        makeMove(&copy, *cur);
        firstMove = NULL;
        score = -alphaBetaMax(-beta, -alpha, depthleft - 1, copy, !player);
        if(board_count > MAX_BOARDS)
            break;

        freeGame(copy);
        if(score > alpha)
        alpha = score;

        if (beta <= alpha)
            break;
        cur = cur->next;
    }
    firstMove=tmp;
    freeMoves();

    if(!did_move)
        alpha = evaluate(game)*(player*2-1);
    return alpha;
}

Solution

  • A fast chess engine relies on two things: Caching the evaluation of positions, and the alpha/beta strategy. Caching positions and making it thread safe and fast is hard. The alpha/beta strategy relies on the seemingly best move being completely evaluated before you start evaluating other moves. This also makes it tough to use multiple threads.

    Beginner composer to Mozart: "Can you tell me how to compose a symphony"? Mozart to beginner: "Maybe at your young age you should try something easier first. " Beginner to Mozart: "But you wrote symphonies when you were much younger than I am now. " Mozart to beginner: "True, but I didn't have to ask anyone".