1

std::atomic を使用して、チェス AI の一部のスレッドを協調的に停止しようとしています。StopPondering() を呼び出したときにスレッドが実行され続ける理由がわかりません。StopPondering で中断すると、Searching が正しく設定されていることがわかりますが、2 つのスレッドのいずれかで中断しても、その値は 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 シングルトンは 1 つしかなく、すべてが期待どおりに機能しています。失敗してごめんなさい。

4

0 に答える 0