Creating a Thread

< BACK  NEXT >
[oR]

Threads are created by calling the function CreateThread. The function is passed an address of a function (the "thread function") that the new thread will start executing, in much the same way the primary thread starts executing WinMain as an entry point into the application. The thread function always has the following prototype:

 DWORD WINAPI ThreadProc(LPVOID lpParameter); 

The function is passed an LPVOID pointer that can be used for passing information into the thread from the thread that calls CreateThread. The function returns a DWORD which is the thread exit code. The thread exit code is used in much the same way as the process exit code described earlier in this chapter.

In Listing 5.7 CreateThread is called to create a new thread that starts executing the code in the thread function MyThreadProc1. The thread function displays a message and then returns. The thread terminates automatically on returning from the thread function in much the same way a process terminates when a return is made from WinMain.

Listing 5.7 Creates a thread
 DWORD WINAPI MyThreadProc1(LPVOID lpParameter) {   cout   _T("Message from the thread")   endl;   return 0; } void Listing5_7() {   HANDLE hThread;   DWORD dwThreadId;   hThread = CreateThread(NULL, 0, MyThreadProc1,       NULL, 0, &dwThreadId);   if(hThread == NULL)     cout   _T("Could not create thread")   endl;   else   {     CloseHandle(hThread);     cout   _T("Thread Created")   endl;   } } 

Table 5.6 shows the parameters for the CreateThread function. A thread has an identifier that is used when calling certain thread functions and is like a process identifier. The function returns a kernel object handle that should be closed by calling CloseHandle.

Table 5.6. CreateThread Creates a new thread
CreateThread
LPSECURITY_ATTRIBUTES lpThreadAttributes Ignored, pass as NULL
DWORD dwStackSize Ignored, pass as 0
LPTHREAD_START_ROUTINE lpStartAddress Pointer to the thread function
LPVOID lpParameter Pointer to data that is passed in to the LPVOID lpParameter parameter in the thread function
DWORD dwCreationFlags CREATE_SUSPENDED to create the thread in a suspended state, or 0 to create a thread that is running
LPDWORD lpThreadId DWORD pointer that receives the thread's identifier
HANDLE Return Value Thread's kernel object handle, or NULL on failure

Unlike the Windows NT/98/2000 operating systems, in Windows CE a thread is always created with a default stack size of 58 KB. Note this is 58 KB of virtual address space, and physical memory is only allocated as the stack grows.


< BACK  NEXT >


Windows CE 3. 0 Application Programming
Windows CE 3.0: Application Programming (Prentice Hall Series on Microsoft Technologies)
ISBN: 0130255920
EAN: 2147483647
Year: 2002
Pages: 181

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net