lundi 23 mai 2016

std::atomic

I am trying to use a std::atomic to cooperatively halt some threads in my chess AI. I can't figure out why my threads continue to run when I call StopPondering(). If I break in StopPondering I see Searching get set correctly, but if I break in either of the two threads, its value is still true. I'm using VS 2013 on Windows 8.1 The relevant subset of the code is below.

AI0.h

#pragma once
#include "AI.h"
#include <thread>
#include <atomic>

class AI0 : public AI
{
public:
    virtual void Ponder(Game game, U8 depth = 0) override;
    virtual void StopPondering() override;
private:

    std::thread* SearchThread;
    std::thread* InfoThread;

    std::atomic<bool> Searching;

    void search(GameState state);
    void SendInfo();
}

AI0.cpp

#include "stdafx.h"
#include "AI0.h"
#include "InterfaceLayer.h"
#include <algorithm>
#include <chrono>

AI0::AI0()
{
    Searching = ATOMIC_VAR_INIT(false);
    SearchThread = nullptr;
    InfoThread = nullptr;
}
void AI0::Ponder(Game game, U8 depth)
{
    SearchThread = new std::thread(&AI0::search, this, game.GetState());
    InfoThread = new std::thread(&AI0::SendInfo, this);
    SearchThread->detach();
    InfoThread->detach();
}

void AI0::StopPondering()
{
    Searching.store(false);
}

void AI0::search(GameState state)
{
    while (Searching.load())
    {
        //Search code.
        //Sets some global data which I do see correctly on main thread.
    }
}

void AI0::SendInfo()
{
    while (Searching.load())
    {
        //Code to update interface layer about search progress.
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

I apologize for my inconsistent capitalization.

Aucun commentaire:

Enregistrer un commentaire