Platform SDK: DLLs, Processes, and Threads |
The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute. Typically, the starting address is the name of a function defined in the program code. This function takes a single parameter and returns a DWORD value. A process can have multiple threads simultaneously executing the same function.
The following example demonstrates how to create a new thread that executes the locally defined function, ThreadFunc.
DWORD WINAPI ThreadFunc( LPVOID lpParam ) { char szMsg[80]; wsprintf( szMsg, "ThreadFunc: Parameter = %d\n", *lpParam ); MessageBox( NULL, szMsg, "Thread created.", MB_OK ); return 0; } VOID main( VOID ) { DWORD dwThreadId, dwThrdParam = 1; HANDLE hThread; hThread = CreateThread( NULL, // no security attributes 0, // use default stack size ThreadFunc, // thread function &dwThrdParam, // argument to thread function 0, // use default creation flags &dwThreadId); // returns the thread identifier // Check the return value for success. if (hThread == NULL) ErrorExit( "CreateThread failed." ); CloseHandle( hThread ); }
For simplicity, this example passes a pointer to a DWORD value as an argument to the thread function. This could be a pointer to any type of data or structure, or it could be omitted altogether by passing a NULL pointer and deleting the references to the parameter in ThreadFunc.
It is risky to pass the address of a local variable if the creating thread exits before the new thread, because the pointer becomes invalid. Instead, either pass a pointer to dynamically allocated memory or make the creating thread wait for the new thread to terminate. Data can also be passed from the creating thread to the new thread using global variables. With global variables, it is usually necessary to synchronize access by multiple threads. For more information about synchronization, see Synchronizing Execution of Multiple Threads.
In processes where a thread might create multiple threads to execute the same code, it is inconvenient to use global variables. For example, a process that enables the user to open several files at the same time can create a new thread for each file, with each of the threads executing the same thread function. The creating thread can pass the unique information (such as the file name) required by each instance of the thread function as an argument. You cannot use a single global variable for this purpose, but you could use a dynamically allocated string buffer.
The creating thread can use the arguments to CreateThread to specify the following:
You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.