Skip to content

Instantly share code, notes, and snippets.

@pbalduino
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbalduino/55c262be68742472734a to your computer and use it in GitHub Desktop.
Save pbalduino/55c262be68742472734a to your computer and use it in GitHub Desktop.
Memory leak with Windows API
#include <iostream>
#include <Windows.h>
#include <string>
namespace windows_threads
{
class THREAD_PARAM
{
public:
std::string name;
unsigned int pause;
THREAD_PARAM(std::string _name, int _pause)
{
name = _name;
pause = _pause;
}
};
typedef THREAD_PARAM* PTHREAD_PARAM;
DWORD WINAPI double_worker(LPVOID parameter);
void testTwoThreadsWithWaitForMultipleObjectsFalse();
}
DWORD WINAPI windows_threads::double_worker(LPVOID parameter)
{
PTHREAD_PARAM param = (PTHREAD_PARAM)parameter;
DWORD threadId = GetCurrentThreadId();
std::cout << " [" << threadId << "] inside the thread <" << param->name << ">" << std::endl;
Sleep(param->pause * 1000);
std::cout << " [" << threadId << "] after " << param->pause << " seconds <" << param->name << ">" << std::endl;
return 0;
}
void windows_threads::testTwoThreadsWithWaitForMultipleObjectsFalse()
{
const int THREADS = 2;
DWORD dwThreadIdArray[THREADS];
HANDLE hThreadArray[THREADS];
PTHREAD_PARAM pParamArray[THREADS];
pParamArray[0] = new THREAD_PARAM(std::string("Thread 1"), 5);
pParamArray[1] = new THREAD_PARAM(std::string("Thread 2"), 4);
for (int i = 0; i < THREADS; i++)
{
hThreadArray[i] = CreateThread(NULL, 0, double_worker, pParamArray[i], 0, &dwThreadIdArray[i]);
}
std::cout << "[" << GetCurrentThreadId() << "] Waiting for thread finish" << std::endl;
WaitForMultipleObjects(THREADS, hThreadArray, FALSE, INFINITE);
std::cout << "[" << GetCurrentThreadId() << "] After WaitForMultipleObjects" << std::endl;
for (int i = 0; i < THREADS; i++)
{
if (hThreadArray[i])
{
CloseHandle(hThreadArray[i]);
}
delete pParamArray[i];
}
std::cout << "[" << GetCurrentThreadId() << "] Thread finished" << std::endl;
}
int main()
{
windows_threads::testTwoThreadsWithWaitForMultipleObjectsFalse();
std::cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment