小编Xce*_*ity的帖子

为什么这个C++静态单例永远不会停止?

我在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)

我所知道的:

  • 线程终止
  • 主线程卡在连接中
  • 它与静态有关,如果我使构造函数公开并在main()中创建一个Singleton实例,它将正确终止.

使用Visual Studio 2012.感谢您的建议.

c++ singleton static multithreading c++11

17
推荐指数
3
解决办法
2663
查看次数

让窗口相信它仍然处于焦点中,尽管事实并非如此

我必须处理一个讨厌的 MS Windows 应用程序,它一旦失去焦点就会停止工作。我的问题是,我怎样才能以某种方式欺骗这个应用程序,让它相信它仍然处于焦点,尽管它实际上不是?

我的想法是:

  1. 是否可以仅从该应用程序中抑制相应的“WM”消息?
  2. 我可以向此窗口发送一条虚假消息,使其表现得好像处于焦点状态吗?

c++ windows focus window suppress

4
推荐指数
1
解决办法
4904
查看次数

标签 统计

c++ ×2

c++11 ×1

focus ×1

multithreading ×1

singleton ×1

static ×1

suppress ×1

window ×1

windows ×1