C++ でシングルトン (静的バージョン) を実装しました。私はこのパターンと潜在的なスレッド セーフの問題に関するすべての論争を知っていますが、なぜこの正確な実装が停止しないのか興味があります。プログラムは決して終了せず、最後にデッドロック状態のままです。
singleton.h:
#pragma once
#include <thread>
#include <atomic>
class Singleton
{
public:
static Singleton& getInstance();
private:
std::thread mThread;
std::atomic_bool mRun;
Singleton();
~Singleton();
void threadFoo();
};
シングルトン.cpp
#include "singleton.h"
Singleton& Singleton::getInstance()
{
static Singleton instance;
return instance;
}
Singleton::Singleton()
{
mRun.store(true);
mThread = std::thread(&Singleton::threadFoo, this);
}
Singleton::~Singleton()
{
mRun.store(false);
if(mThread.joinable())
mThread.join();
}
void Singleton::threadFoo()
{
while(mRun)
{
}
}
main.cpp
#include "singleton.h"
int main()
{
Singleton::getInstance();
return 0;
}
私がすでに知っていること:
- スレッドは終了します
- メインスレッドが結合でスタックしている
- コンストラクターを公開し、main() で Singleton のインスタンスを作成すると、正しく終了します。
Visual Studio 2012 を使用しています。アドバイスありがとうございます。