HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
| Parameter | Description |
|---|---|
| lpThreadAttributes | A pointer to a SECURITY_ATTRIBUTES structure that specifies the security attributes of the new thread. If this parameter is NULL, the thread gets a default security descriptor, and the new thread inherits its creator's process-handle access-control list (ACL). |
| dwStackSize | The initial region size, in bytes, of the stack allocated for the new thread. If this parameter is 0, the server allocates a stack of the same size as that used by the calling thread of the process. |
| lpStartAddress | A pointer to the application-defined function of type LPTHREAD_START_ROUTINE that the thread should execute. This is a pointer to the beginning of the routine. |
| lpParameter | A pointer to a variable to be passed to the thread function. |
| dwCreationFlags |
Flags that control the thread's creation.
|
| lpThreadId | A pointer to a 32-bit variable that receives the thread identifier of the new thread. If this parameter is NULL, the thread identifier is not returned. |
If the function succeeds, the return value is a handle to the new thread. If the function fails, the return value is NULL. To get extended error information, call GetLastError.
The thread runs in the address space of the calling process and uses the process's handle table. The thread continues executing until it calls the ExitThread function, the from-process thread of execution returns from the thread function, or the process terminates.
#include <windows.h>
#include <iostream>
// Thread function
DWORD WINAPI MyThreadFunction(LPVOID lpParam) {
int threadNum = *(int*)lpParam;
std::wcout << L"Hello from thread " << threadNum << L"!" << std::endl;
return 0;
}
int main() {
HANDLE hThread;
DWORD threadID;
int threadNum = 1;
// Create the thread
hThread = CreateThread(
NULL, // Default security attributes
0, // Default stack size
MyThreadFunction, // Thread function
&threadNum, // Parameter to thread function
0, // Run immediately
&threadID); // Returns the thread identifier
if (hThread == NULL) {
std::cerr << "Failed to create thread. Error: " << GetLastError() << std::endl;
return 1;
}
std::wcout << L"Thread created successfully with ID: " << threadID << std::endl;
// Wait for the thread to finish
WaitForSingleObject(hThread, INFINITE);
// Close the thread handle
CloseHandle(hThread);
std::wcout << L"Main thread exiting." << std::endl;
return 0;
}