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 threadDWORD 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.
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.
|