Visual Studio bogotobogo example 01

From Minor Miracle Software
Revision as of 14:11, 24 June 2019 by WikiSysop (talk | contribs) (Created page with " bogotobogo Win32 thread example 1[https://www.bogotobogo.com/cplusplus/multithreading_win32A.php] =Examples Using a Counter= Windows multithreading functions require #includ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

bogotobogo Win32 thread example 1[1]

Examples Using a Counter

Windows multithreading functions require #include <windows.h> in the program.

Each thread has its own stack. The stack size is specified in bytes using the stackSize parameter, 2nd argument, for the CreateThread( ) function. If this integer value is zero, then the new thread stack size will equal the creating thread stack size.

Sample Code
#include "stdafx.h"
#include "2012vcThreads.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#include <windows.h>
#include <iostream>


// The one and only application object

CWinApp theApp;

using namespace std;

DWORD WINAPI myThread(LPVOID lpParameter)
{
	unsigned int& myCounter = *((unsigned int*)lpParameter);
	while(myCounter < 0xFFFFFFFF)
            ++myCounter;
	return 0;
}

int main(int argc, char* argv[], char* envp[])
{
	int nRetCode = 0;

	HMODULE hModule = ::GetModuleHandle(NULL);

	if (hModule != NULL)
	{
		// initialize MFC and print and error on failure
		if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
		{
			// TODO: change error code to suit your needs
			printf( "Fatal Error: MFC initialization failed\n" );
			nRetCode = 1;
		}
		else
		{
			// TODO: code your application's behavior here.
			unsigned int myCounter = 0;
			DWORD myThreadID;
			HANDLE myHandle = CreateThread(0, 0, myThread, &myCounter, 0, &myThreadID);
			char myChar = ' ';
			while(myChar != 'q') {
				cout << myCounter << endl;
				myChar = getchar();
			}
	
			CloseHandle(myHandle);



			// Wait for keystroke
			printf( " Press any key to continue.\n" );
			getchar();

		}
	}
	else
	{
		// TODO: change error code to suit your needs
		printf( "Fatal Error: GetModuleHandle failed\n" );
		nRetCode = 1;
	}

	return nRetCode;
}

Output
0
2107603026
2374378076
2555231882
2732544120
3190532868
3355344811
3593650432
3794190989
4101563828
4294967295
...

Internal Links

Parent Article: Visual Studio Threads