简体   繁体   中英

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. 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. 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). 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:

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.

Thank you for your help

Use std::thread for thread creation. Pass pointer to thread's entry point to its constructor as a lambda of member function pointer. Instances of std::thread may reside in the private section of your class. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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