简体   繁体   中英

How to create a loader thread in directx

I have a game engine which used Directx 9 for rendering. I would like to be able to load sprite graphics in whilst the main update and render loop executes. Currently the engine has one main update and render loop so any loading done in this will pause the main loop whilst the graphics load.

I was looking at POSIX threads to do this. I have created the thread function and included mutex locks but the code crashes when its ran.

Here is the thread function:

void GameApp::InternalThreadEntry()
{
    pthread_mutex_lock (&mutex);

    for(int i = 0; i < MAX_NUMBER; i++)
    {
        test_loader_sprites[i].loadImage(window1,"Test_Image.tga");
    }

    has_finishd_loading = true;

    pthread_mutex_unlock (&mutex);
}

The Code crashes in my engines render function. Im sure this is because the directx device, which is a member of the window1 instance, is accessed for loading by the thread whilst the main application accesses it for rendering.

Could you shed a little light on where im going wrong. Im new to using threads.

All the best, Martin

Threading is often a wolf in sheeps clothing. It looks to solve so many problems, but in reality can cause so many more than they solve. Fortunately you have what many would believe a valid scenario to use an additional thread.

Having written a similar loader myself a while back, your problem looks to indeed be that you are accessing Window1 while its in use elsewhere. Basically, does your main thread do anything with Window1 while the thread would be running. If so then that would indicate it to be the problem.

The solution I found was to properly separate out data storage from the renderer. You can load in the data to a store in a thread. Once that has done, pass that information in the store to the main thread at the end of the thread (or move it directly in the main thread later). This avoids dependency on your Window1 object within the thread.

It would be a good idea to do some further reading on threads before embarking on a larger scale scenario it sounds you are working on. Working with threads is one of the more fiddly and complicated areas of software design, and from experience you can't learn them well enough.

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