Last active
November 11, 2015 20:26
-
-
Save dnikku/b41dccf1f56d4005241c to your computer and use it in GitHub Desktop.
_beginthreadex/CreateThread leaks when using CRT or not (with one wait)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
/* | |
stdafx.f: | |
#include <time.h> | |
#include <stdio.h> | |
#include <tchar.h> | |
#include <Windows.h> | |
#include <process.h> | |
*/ | |
static LONG g_scheduledThreads = 0; | |
static LONG g_executedThreads = 0; | |
static volatile INT64 g_size = 0; | |
void printCounts(int step) { | |
printf(" step:%d, scheduled:%d, completed:%d, some:%d\n", step, g_scheduledThreads, g_executedThreads, g_size); | |
} | |
void executeThread(int v){ | |
//leaks: | |
time_t tt = _time64(NULL); | |
//leaks: FILETIME ft; GetSystemTimeAsFileTime(&ft); | |
//no leaks: char sz[524 * 1024]; sprintf(sz, "Salutare de la mare"); | |
//no leaks: SYSTEMTIME stm; GetSystemTime(&stm); g_size += stm.wSecond; | |
InterlockedAdd(&g_executedThreads, v); | |
} | |
static unsigned int __stdcall _beginthreadex_wrapper(void *arg) { | |
executeThread(1); | |
return 0; | |
} | |
bool _beginthreadex_factory(int step) { | |
InterlockedAdd(&g_scheduledThreads, 1); | |
//g_scheduledThreads++; | |
unsigned int id; | |
HANDLE handle = (HANDLE)_beginthreadex(NULL, | |
6400 * 1024, _beginthreadex_wrapper, NULL, STACK_SIZE_PARAM_IS_A_RESERVATION, &id); | |
if (handle == 0) { | |
DWORD lastError = GetLastError(); | |
printf("_beginthreadex failed. err(%d); errno(%d). exiting ...\n", lastError, errno); | |
return false; | |
} | |
else { | |
DWORD status = WaitForSingleObject(handle, INFINITE); | |
if (STATUS_WAIT_0 != status) printf(" Iter:%d . failed wait thread: %d", step, status); | |
CloseHandle(handle); | |
return true; | |
} | |
} | |
int _tmain(int argc, _TCHAR* argv[]) { | |
printf("starting ...\n"); | |
bool(*f_wrapper) (int) = _beginthreadex_factory; | |
while (true) { | |
int i; | |
for (i = 0; i < 1000000; i++) { | |
if (!f_wrapper(i)){ | |
printCounts(i); | |
Sleep(5 * 1000); // wait some time ... | |
printCounts(i); | |
// try to create 10 more threads | |
for (int j = 0; j < 10; j++) f_wrapper(i + j + 1); | |
break; // exit from for ... | |
} | |
if (i % 5000 == 0) printCounts(i); // print progress | |
} | |
Sleep(4 * 1000); // wait to stop all threads | |
printCounts(i); | |
printf("rerun loop:"); | |
getchar(); // press enter to rerun | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment