我在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();
};
Run Code Online (Sandbox Code Playgroud)
singleton.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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include "singleton.h"
int main()
{
Singleton::getInstance();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我所知道的:
使用Visual Studio 2012.感谢您的建议.
我必须处理一个讨厌的 MS Windows 应用程序,它一旦失去焦点就会停止工作。我的问题是,我怎样才能以某种方式欺骗这个应用程序,让它相信它仍然处于焦点,尽管它实际上不是?
我的想法是: