1

我正在尝试使用 std::atomic 来合作停止我的国际象棋 AI 中的一些线程。当我调用 StopPondering() 时,我无法弄清楚为什么我的线程继续运行。如果我中断 StopPondering 我会看到 Searching 设置正确,但如果我中断两个线程中的任何一个,它的值仍然是 true。我在 Windows 8.1 上使用 VS 2013 代码的相关子集如下。

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));
    }
}

我为我不一致的大小写道歉。

- - - - -编辑 - - - - -

问题解决了。我愚蠢地创建了多个 AI0 实例,而且,正如某些人所怀疑的那样,我没有在产生线程的同一个实例上调用 StopPondering(),这肯定是内存泄漏。我现在只有一个 AI0 单例,一切都按预期工作。很抱歉失败了。

4

0 回答 0