简体   繁体   English

C ++-(DirectX11)如何在类中使用线程

[英]C++ - (DirectX11) How to use a thread within a class

I currently have a project using DirectX11, that generates random terrain based on the Hill algorithm. 我目前有一个使用DirectX11的项目,该项目基于Hill算法生成随机地形。 I have a set up where by you can change the inputs on the terrain (seed, number of hills etc) and then reinitialize and watch the terrain get generated hill by hill. 我有一个设置,您可以在其中更改地形(种子,山丘数量等)的输入,然后重新初始化并观看地形逐山生成。 The issue with this is that (as you would expect) there is a large FPS loss, but also things like the camera will stutter when attempting to move it. 这样的问题是(如您所料)FPS损失很大,但是在尝试移动照相机时,照相机也会结结巴巴。 Essentially, what I want to do is create a thread for the terrain hill step, so that the generation doesn't interfere with the frame time and therefor the camera (so the camera can still move seamlessly). 本质上,我想做的是为terrain hill step创建一个线程,以使生成不会干扰帧时间,从而不会干扰相机(因此相机仍可以无缝移动)。 I've looked at a few resources but I'm still not understanding threads properly. 我看了一些资源,但我仍然无法正确理解线程。

Checking when to reinitialize the terrain, during the update method: 在更新方法期间,检查何时重新初始化地形:

void CThrive::Update(float frameTime)
{
    CKeyboardState kb = CKeyboardState::GetKeyboardState(mWindow->GetHWND());

    mCamera->Update(kb, frameTime);

    if (mGui->Reint())
    {
        SafeDelete(mTerrain);
        mTerrain = new CTerrain(mGui->GetTerrSize(), mGui->GetTerrMin(), mGui->GetTerrMax(), mGui->GetTerrNumHills(), mGui->GetTerrSeed());

        mNewTerrain = true;
        mGui->SetReint(false);
    }

Calling method to generate new hills, during the render method: 在render方法期间,调用方法以生成新的山丘:

void CThrive::Render()
{
    if (mNewTerrain)
    {
        reintTerrain();
    }

    MainPass();
}

Method used to add to the terrain: 用于添加到地形的方法:

void CThrive::reintTerrain()
{
    if (!mTerrain->GenerationComplete())
    {
        mTerrain->GenerateStep(mGraphicsDevice->GetDevice());
    }
    else
    {
        mNewTerrain = false;
    }
}

I assume I'd create a thread for reintTerrain, but I'm not entirely sure how to properly make this work within the class, as I require it to stop adding hills when it's finished. 我以为为reintTerrain创建了一个线程,但是我不完全确定如何在类中正常进行此工作,因为我要求它在完成后停止添加山丘。

Thank you for your help 谢谢您的帮助

Use std::thread for thread creation. 使用std::thread thread创建线程。 Pass pointer to thread's entry point to its constructor as a lambda of member function pointer. 将指向线程入口点的指针传递给其构造函数,作为成员函数指针的lambda。 Instances of std::thread may reside in the private section of your class. std::thread实例可能位于您的类的private部分中。 Accesses to shared object's fields used by multiple threads should be protected by fences ( std::atomic<> , std::atomic_thread_fence ) in order to avoid cache coherency problems. 为了避免高速缓存一致性问题,对多个线程使用的共享对象字段的访问应使用围栅( std::atomic<>std::atomic_thread_fence )保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM