【问题标题】:Detach a static const std::thread?分离一个静态常量 std::thread?
【发布时间】:2020-07-06 18:09:26
【问题描述】:

这是违法的吗?如何使用private 隐藏这个全局线程实例?它似乎在没有 const 的情况下也能工作,但我仍然想 const 它只是为了安心。

struct AbstractImage {
private:
    static void LoadImages();
    static const std::thread ImageLoader;
};
...
const std::thread AbstractImage::ImageLoader( AbstractImage::LoadImages );

void AbstractImage::LoadImages() {
    ImageLoader.detach();
}
'void std::thread::detach(void)': cannot convert 'this' pointer from 'const std::thread' to 'std::thread &'

【问题讨论】:

  • detach 需要改变线程对象的状态。正如您从不是 const 方法的事实中看到的那样。所以不,你不能在 const 线程上分离。 “我仍然想为了安心而对其进行构造。”什么心安?如果你需要分离,你需要它是可变的。
  • 我很乐意不分离它,否则它会在程序退出时弹出一个愚蠢的断言失败对话框。
  • 为什么需要一个全局的std::thread 对象?为什么不在启动时调用一个函数,并让该函数使用它在退出之前分离的本地std::thread
  • 回复。 "...it pops up a silly assert failed dialog at program exit",那是因为在调用它的析构函数之前,你(可能)不是 joining 它。
  • @RemyLebeau 我使用私有成员,以便它可以调用私有结构函数

标签: c++ static constants stdthread


【解决方案1】:

您不能在const std::thread 对象上调用detach(),因为detach() 需要修改std::thread 的状态。

在这种情况下,我建议根本不要使用静态 std::thread 对象。特别是因为它是一次性使用的线程,所以一旦线程开始运行,std::thread 对象就不需要挂起。在另一个函数或静态方法中使用本地的std::thread 变量,然后您可以根据需要在启动时调用它,例如:

struct AbstractImage
{
private:
    static void LoadImages();

    struct LoadImagesStarter
    {
        LoadImagesStarter()
        {
            std::thread(AbstractImage::LoadImages).detach();
        }
    };

    static const LoadImagesStarter ImageLoader;
};
...

const AbstractImage::LoadImagesStarter AbstractImage::ImageLoader;

void AbstractImage::LoadImages()
{
    ...
}

Live Demo

或者:

struct AbstractImage
{
private:
    static void LoadImages();

    friend void LoadImagesStarter();
};
//...

void AbstractImage::LoadImages()
{
    ...
}

__attribute__((constructor)) void LoadImagesStarter()
{
    std::thread(AbstractImage::LoadImages).detach();
}

/* or, if your compiler supports this:
void LoadImagesStarter()
{
    std::thread(AbstractImage::LoadImages).detach();
}
#pragma startup LoadImagesStarter 100
*/

Live Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多