Click to See Complete Forum and Search --> : Need help using threads for a loader function


Valor Knight
February 9th, 2006, 02:19 AM
After looking a bunch of stuff up after I got that reply (thanks), I have come to a couple of problems.

I am trying to lock a pointer to data, can I just lock it in the loading class, or do I have to use a critical section / mutex everywhere I want to read or write the data? Currently I am using a critical section and have found 3/4 time I load the program, I get a critical error, but the 4th time everything works as expected. I assume that is due to the data not being "locked" for the current thread. Would using a mutex stop this, and how would I stop these errors relating to the data not being locked?


Here is (most of) my thread code

void Phoenix::InitThread()
{
_hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadMain, (void*)this, 0, &_ThreadID );
}

//////////////////////////////////////////////////////////
unsigned int __stdcall Phoenix::ThreadMain(LPVOID param)
{
Phoenix* loader = (Phoenix*)param;

while(loader->RunThread());//keep running the thread until RunThread() returns false


_endthreadex( 0 );
return 0;
}


bool Phoenix::RunThread()
{
Sleep(1000);

while(_TerrainQueue.size() > 0)
{
EnterCriticalSection( &_cs );

_TerrainQueue[0].pTerrain->Init(_pDevice, "data\\level\\world\\003007", _TerrainProperties.MapDimensions, _TerrainProperties.PatchSize, _TerrainProperties.TerrainXZSpacing, _TerrainProperties.TerrainYScale, _TerrainProperties.TerrainTextureRepeat, _TerrainProperties.TerrainFilterAmount);
*_TerrainQueue[0].pLoaded = true;

_TerrainQueue.erase(_TerrainQueue.begin());

LeaveCriticalSection( &_cs );
}

return _Active;
}

////////////////////////////////////////////////////
//Loading functions
void Phoenix::LoadTerrain(cTerrain *terrain, char *filename, bool *loadflag)
{
sTerrain newload;
newload.pTerrain = terrain;
newload.pFilename = filename;
newload.pLoaded = loadflag;

//
EnterCriticalSection( &_cs );
//
_TerrainQueue.push_back(newload);
//
LeaveCriticalSection( &_cs );

}


Thanks

kirants
February 9th, 2006, 01:07 PM
Some pointers here:
Where can I find references on Multithreading? (http://www.codeguru.com/forum/showthread.php?p=1222389#post1222389)
CodeGuru: Win32 Thread Synchronization, Part I: Overview (http://www.codeguru.com/Cpp/W-D/dislog/win32/article.php/c9823)
Queue implementation (http://www.codeguru.com/forum/showthread.php?t=367063&highlight=queue)

Valor Knight
February 10th, 2006, 11:49 PM
Thanks for the links, they were the best info I have found on threads.
I have revised my question above to reflect my changes.

kirants
February 13th, 2006, 12:08 PM
It's not clear. For example, one cannot see where the LoadTerrain is called from . Also, InitThread