Game Development Reference
In-Depth Information
++dwCount;
++g_UnprotectedTotal;
}
return TRUE;
}
void CreateThreads()
{
for (int i=0; i<20; i++)
{
CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) ThreadProc,
&g_maxLoops, // thread parameter is how many loops
0,
// default creation flags
NULL);
// receive thread identifier
}
}
To create a thread, you call the CreateThread() API with a pointer to a function
that will run as the thread procedure. The thread will cease to exist when the thread
procedure exits or something external stops the thread, such as a call to Terminate-
Thread() . The thread procedure, ThreadProc , takes one variable, a void pointer that
you may use to send any bit of data your thread procedure needs. In the previous exam-
ple, a DWORD was set to the number of loops and used as the thread parameter. The
thread can be started in a suspended state if you set the default creation flags to CRE-
ATE_SUSPENDED ,inwhichcaseyou
'
ll need to call ResumeThread(m_hThread) to
get it started.
Take special note of where the parameter to the thread process is stored, because it is
a global. Had it been local to the CreateThreads() function, it would have been
stored on the stack. The address of this would have been passed to the thread proce-
dures, and goodness knows what it would have in it at any given moment. This is a
great example of how something seemingly trivial can have a huge effect on how
your threads run.
The Stack Can Be a Dangerous Place
Be careful about where you store data that will be accessed by thread
procedures. The stack is right out, since it will be constantly changing.
Allocate specific memory for your thread procedures or store them globally.
 
Search WWH ::




Custom Search