Listing 1: heaptest.c Multithreaded memory tester.
#define WIN32_LEAN_AND_MEAN #include <windows.h> #include <process.h> #include <stdio.h> #include <stdlib.h> /* compile with cl /MT heaptest.c */ /* to switch to the system heap issue the following command before starting heaptest from the same command line set __MSVCRT_HEAP_SELECT=__GLOBAL_HEAP_SELECTED,1 */ /* structure transfers variables to the worker threads */ typedef struct tData { int maximumLength; int allocCount; } threadData; void printUsage(char** argv) { fprintf(stderr,"Wrong number of parameters.\nUsage:\n"); fprintf(stderr,"%s threadCount maxAllocLength allocCount\n\n", argv[0]); exit(1); } unsigned __stdcall workerThread(void* myThreadData) { int count; threadData* myData; char* dummy; srand(GetTickCount()*GetCurrentThreadId()); myData=(threadData*)myThreadData; /* now let us do the real work */ for(count=0;count<myData->allocCount;count++) { dummy=(char*)malloc((rand()%myData->maximumLength)+1); free(dummy); } _endthreadex(0); /* to satisfy compiler */ return 0; } int main(int argc,char** argv) { int threadCount; int count; threadData actData; HANDLE* threadHandles; DWORD startTime; DWORD stopTime; DWORD retValue; unsigned dummy; /* check parameters */ if(argc<4 || argc>4) printUsage(argv); /* get parameters for this run */ threadCount=atoi(argv[1]); if(threadCount>64) threadCount=64; actData.maximumLength=atoi(argv[2])-1; actData.allocCount=atoi(argv[3]); threadHandles=(HANDLE*)malloc(threadCount*sizeof(HANDLE)); printf("Test run with %d simultaneous threads:\n",threadCount); startTime=GetTickCount(); for(count=0;count<threadCount;count++) { threadHandles[count]=(HANDLE)_beginthreadex(0,0, &workerThread, (void*)&actData,0,&dummy); if(threadHandles[count]==(HANDLE)-1) { fprintf(stderr,"Error starting worker threads.\n"); exit(2); } } /* wait until all threads are done */ retValue=WaitForMultipleObjects(threadCount,threadHandles ,1,INFINITE); stopTime=GetTickCount(); printf("Total time elapsed was: %d milliseconds", stopTime-startTime); printf(" for %d alloc operations.\n", actData.allocCount*threadCount); /* cleanup */ for(count=0;count<threadCount;count++) CloseHandle(threadHandles[count]); free(threadHandles); return 0; } /* End of File */