C++ _beginthreadex: Create Multiple Threads
In C++, you can create multiple threads using the beginthreadex function. It is a function provided by the Windows API to create a new thread.
The following are the steps to create multiple threads using the beginthreadex function:
- Include header file:
#include <Windows.h>
- Define the thread function:
DWORD WINAPI ThreadFunction(LPVOID lpParam) {
// 线程的具体操作
// 使用lpParam参数传递需要的数据
return 0;
}
The return type of the thread function is DWORD, and the parameter type is LPVOID. LPVOID can be used to pass any type of data and requires type conversion internally.
- Create a thread:
HANDLE hThread;
unsigned int threadId;
hThread = (HANDLE)_beginthreadex(NULL, 0, ThreadFunction, lpParam, 0, &threadId);
The parameters of the _beginthreadex function are in the following order: security attributes, default to NULL; stack size, default to 0; thread function, which is the ThreadFunction defined in the previous step; parameters passed to the thread function, can be of any data type; creation flags for the thread, 0 indicates immediate creation; a reference to the thread ID, used to obtain the thread’s ID.
- Wait for the thread to finish.
WaitForSingleObject(hThread, INFINITE);
Wait for the thread to finish using the WaitForSingleObject function. The first parameter is the thread handle, and the second parameter is the wait time. Using INFINITE means waiting indefinitely until the thread finishes.
- Close the thread handle.
CloseHandle(hThread);
Use the CloseHandle function to close the thread handle and release resources.
The detailed steps for creating multiple threads using the beginthreadex function have been outlined above. It is important to note that the created threads will execute in the specified thread function, allowing the passing of necessary data through parameters and the transfer of thread execution results through return values.