To create a thread in Windows, you can use the following steps:
Include the windows.h header file to gain access to the necessary functions and types for thread management.
Define the function that will be executed in the thread. This function should have the prototype: DWORD WINAPI ThreadFunction(LPVOID lpParam). The DWORD is the return type and WINAPI is the calling convention. LPVOID is a generic pointer type used to pass data to the thread function. Note that the entry point of a thread function must match this prototype.
In your main program, call the CreateThread function to create a new thread. The function has the following prototype:
HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId );
The lpThreadAttributes parameter can be set to NULL, and the dwStackSize parameter can be set to 0 to use the default stack size. The lpStartAddress parameter should be set to the address of your thread function. The lpParameter parameter can be used to pass data to the thread function. The dwCreationFlags parameter can be set to 0 for default behavior. The lpThreadId parameter can be NULL if you don't need to retrieve the thread ID.
Handle the created thread using the returned HANDLE. You can call functions like WaitForSingleObject to wait for the thread to finish executing, or TerminateThread to forcibly terminate it.
Here's an example:
#include <windows.h>
#include <iostream>
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
std::cout << "Hello from thread!" << std::endl;
return 0;
}
int main() {
HANDLE hThread;
DWORD threadId;
hThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadId);
if (hThread == NULL) {
std::cerr << "Failed to create thread." << std::endl;
return 1;
}
// Wait for the thread to finish executing
WaitForSingleObject(hThread, INFINITE);
// Cleanup
CloseHandle(hThread);
return 0;
}
In this example, a new thread is created using CreateThread, and its entry point is the ThreadFunction. The main program waits for the thread to finish using WaitForSingleObject and then closes the thread handle.