- 1 year ago
Pass non-dynamic memory allocation to CreateThread() function
The CreateThread()
function in Windows is designed to work with thread functions that are dynamically allocated, typically using malloc()
or new
. However, if you want to pass a non-dynamic memory allocation (such as a stack-allocated function or a class member function) to CreateThread()
, you can achieve it by using a static function or a global function as a wrapper.
Here's an example of how you can pass a non-dynamic memory allocation to CreateThread()
using a static function as a wrapper:
cpp#include <Windows.h>
// Non-dynamic memory allocation function
void MyThreadFunction()
{
// Thread logic here
// ...
}
// Wrapper function
static DWORD WINAPI ThreadWrapper(LPVOID lpParameter)
{
MyThreadFunction();
return 0;
}
int main()
{
// Create the thread using the wrapper function
HANDLE hThread = CreateThread(NULL, 0, ThreadWrapper, NULL, 0, NULL);
// Check if thread creation was successful
if (hThread != NULL)
{
// Wait for the thread to finish
WaitForSingleObject(hThread, INFINITE);
// Close the thread handle
CloseHandle(hThread);
}
return 0;
}
In this example, the MyThreadFunction()
is a non-dynamic memory allocation function that contains the actual logic of the thread. We create a static function called ThreadWrapper()
that acts as a wrapper for MyThreadFunction()
. The ThreadWrapper()
function is then passed to CreateThread()
.
Inside ThreadWrapper()
, we call MyThreadFunction()
to execute the thread logic. Finally, we wait for the thread to finish using WaitForSingleObject()
and close the thread handle with CloseHandle()
.
By using a static function or a global function as a wrapper, you can pass a non-dynamic memory allocation to CreateThread()
in Windows.