小编Mat*_*out的帖子

安全使用volatile bool强制另一个线程等待?(C++)

我读过的关于volatile的一切都说它永远不会安全,但我仍然倾向于尝试它,而且我还没有看到这个特定场景被宣布为不安全.

我有一个单独的线程渲染场景,从主模拟线程中提取数据.这没有同步,并且工作正常.

问题是当程序退出时,渲染器需要停止从模拟线程中提取数据,然后模拟线程才能安全地自我清理,而不会导致渲染器尝试读取无效内存.

为了实现这一点,我让渲染器在其线程中无限运行:

volatile bool stillRendering;

void RenderThreadFunction()
{
    stillRendering = true;

    while(programRunning)
    {
        renderer->render();
    }

    stillRendering = false;
}
Run Code Online (Sandbox Code Playgroud)

在主程序线程中,当收到windproc退出消息时,我会:

void OnQuit()
{
    programRunning = false;
    while(stillRendering)
    {
    }

    delete application;
}
Run Code Online (Sandbox Code Playgroud)

这样做的目的是确保渲染器在应用程序上调用delete之前停止从应用程序中提取数据.

我首先尝试了这个没有任何volatile关键字,并且它在调试模式下工作,但在发布模式下它挂了.我假设编译器进行了一些优化,导致程序停止检查stillRendering的值.

将volatile添加到stillRendering会导致应用程序在我到目前为止每次测试时成功退出.我不确定为什么"programRunning"不稳定似乎并不重要.

最后,我不确定如何使用volatile为"stillRendering"影响程序的性能.如果使用StillRendering volatile会影响OnQuit()的性能,那对我来说并不重要,但如果它影响RenderThreadFunction()的性能,它对我来说很重要

c++ multithreading boolean volatile thread-safety

8
推荐指数
2
解决办法
3349
查看次数

为什么我允许从const成员函数调用this-> deviceContext-> map()?

我不明白为什么允许这样做:

void Renderer::UpdateTextureFromArray(unsigned int* colors, unsigned int size, TextureData* textureData) const
{
    D3D11_MAPPED_SUBRESOURCE ms;
    this->deviceContext->Map(textureData->texture, 0, D3D11_MAP_WRITE_DISCARD, NULL, &ms);

    memcpy(ms.pData, colors, sizeof(unsigned int) * size * size);
    this->deviceContext->Unmap(textureData->texture, 0);
}
Run Code Online (Sandbox Code Playgroud)

我创建了UpdateTextureFromArray函数const,但我仍然允许在其成员上调用非const函数?

在这种情况下,将函数标记为const是不好的风格?

编辑:澄清一下,如果我有像这样的const函数,它是否对社会"撒谎"?在完美的世界中,这段代码无法编译,对吧?

c++ direct3d const const-correctness direct3d11

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