Thomas Sampson


Leave a comment

C++ Code Timing Snippet


#include <windows.h>

int main(int argc, char* argv[])
{
    __int64 start, end, frequency;
    QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);

    QueryPerformanceCounter((LARGE_INTEGER*)&start);

    Sleep(888);

    QueryPerformanceCounter((LARGE_INTEGER*)&end);

    float time_in_seconds=(end-start) / (float)frequency;

    return 0;
}

Advertisements


Leave a comment

Basic C++ Multi Threading

This is a quick post for anyone who wants to get up and running with multiple threads quickly in C++. I have been doing a fair amount of python programming recently, in particular a 2D networked game, and have realised how useful distributing independent tasks across multiple threads can be. After looking into how best and easiest to translate this experience from python and get a working example going in C++, I am posting the following code which I will attempt to explain beneath.

#include <iostream>
#include <windows.h>
#include <conio.h>
using std::cout;
using std::endl;

int thread_count(0);
int main_thread_count(0);

DWORD_PTR WINAPI threadFunction(void* p)
{
  ++thread_count;
  while(true)
  {
    cout << "Thread "<<(unsigned int)p<<" busy...."<<endl;
  }

  return 0;
}

int main(int argc, char* argv[])
{
  cout << "Starting...."<<endl;

  //Gather processor info
  SYSTEM_INFO si={0,0};
  GetSystemInfo(&si);
  const unsigned int num_cores(si.dwNumberOfProcessors);

  cout << num_cores << " Cores detected"<<endl;

  //Set up thread handles
  HANDLE* thread_handle=new HANDLE[num_cores];
  ZeroMemory(thread_handle,sizeof(HANDLE)*num_cores);

  for(unsigned int core(0);core<num_cores; ++core)
  {
    DWORD_PTR rqd;
    thread_handle[core]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadFunction, (LPVOID)core,     NULL, &rqd);
  }

  cout << "Main thread reached"<<endl;

  std::cin.get();
  std::cin.get();

  //Terminate threads
  DWORD exit_code( 0);
  for(unsigned int core(0);core<num_cores; ++core)
  {
    TerminateThread(thread_handle[core],exit_code);
  }

  delete[] thread_handle;

  return 0;
}

Quick run through!

How many threads to use? A good question! When you first come across threading you may believe it is the answer to every problem and spawn threads in abundance! In the example above I have used the GetSystemInfo() call to gather information about the available CPU’s, then use this information to spawn a thread per cpu. The threads get spawned in the same virtual address space as the parent process and are allocated a stack space of 1mb by default (although this is tweakable). For this reason you could essentially spawn as many threads as you like up to the virtual memory limit of the system, but a separate thread per cpu is usually prefered, and is the recommended approach over at msdn.

Spawning a thread essentially means running some previously declared function in parallel to main, and in this example each new thread runs threadFunction(). In real life this is seemingly useless, you would usually have a specific function and task for each thread such as rendering particles, or listening out on a socket for incoming connections.

Thread handles are used to allow you to make reference and work with your threads after you have created them, for a comprehensive list of thread operations see here. Be sure to use the thread handles to TerminateThread() on each of your threads before exiting the parent process.


Leave a comment

STL algorithm predicates

Just a quick reminder on how to set up a predicate function for an stl algorithm (accumulate shown here) using the () operator on a struct/class.

This arbitrary example accumulates all integer values in bag which are greater than 2. There third parameter to accumulate (the zero) means start accumulating from 0 rather than a given constant.

struct check
{
	int operator()(int l, int r)
	{
		return (r>2)?  (l+r): l;
	}
};

int total=std::accumulate(bag.begin(),bag.end(),0,check());


Leave a comment

Visual Studio Post Build Events

I am currently working on a Visual Studio solution that has multiple projects each building an exe or library to a different directory. My aim was to copy some of the output files all into the same folder as the main application is dependent on the other projects residing in the same directory.

Previously, if I had updated and rebuilt one of the projects in the solution I would manually locate the output file and drag it into the right place. However today I discovered the post build events area in Visual studio (right click solution > Build events). Here you can input your own DOS commands and utilise a bunch of VS environmental macros/variables to create a simple batch script which is automatically executed every time you build/rebuild your solution. Any output from your DOS commands (echo) is printed into the ouput window inline with all the other build information Visual Studio provides during the build process.

Here is a simple example which solved my problem but there are much more advanced techniques you could use with this feature.

echo Copying pre loader application to build directory
copy "$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe" "$(OutDir)"
echo Launching pre loader tool
"$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe"


Leave a comment

Taking control of the message loop!

Intro

Today I found a neat way to access and work with the windows message loop via a class member function using a small hack/workaround. Unless you are working with a command line application you will probably have need to call RegisterClassEx() (a win api function) at some point early on in your program, to register a window with the operating system. In doing so you fill out a WNDCLASSEX structure describing your window, and also setting the message processing callback function (the part we are interested in).

The scenario

As mentioned previously, when setting up our WNDCLASSEX structure we usually pass a non-member function into the structure as a callback mechanism for system/window events (usually names something like MsgProc). This non member function gets invoked when messages are sent to our application from the OS and we can handle them appropriately.

In a lot of situations (especially when developing games applications) we have some kind of manager class responsible for initialising the window, perhaps a graphics api etc, and it would be nice for this manager class to be able to handle the message loop it’s self using a class member function. This is handy as it allows events in the message loop to directly affect the state and behaviour of the manager class.

The problem is that when registering your window, the WNDCLASSEX structure will not take a class member function as a parameter (due to it needing a handle to the class instance at runtime). I have seen and used many hacks to allow a class to handle this job (involving function pointers / static class methods etc etc) but none have been as efficient as the one which follows…

  • Give the WNDCLASSEX structure a non-member function to act as a …”middle man” message loop
  • When calling CreateWindow() pass in a pointer to the class instance (usually “this“)
  • Inside the non member message loop extract this pointer and redirect the call

Example

Here is an example of redirecting the message loop to the WndProc() method of a Manager instance…

Window Setup
//Setup the window class
WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, MainWndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL,"demo", NULL};

//Register window class with OS
RegisterClassEx(&wc);

// "this" is used to let the window know of our manager class instance
CreateWindow("demo", "demo", MODE_WINDOWED, 100, 100, 640, 480, GetDesktopWindow(), NULL, wc.hInstance, this);
Non-member Message Loop
//NON MEMBER MESSAGE LOOP
LRESULT CALLBACK MainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static Manager* app = 0;

	switch( msg )
	{
		case WM_CREATE:
		{
			// Get the pointer to the manager instance we passed
			// into CreateWindow
			CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
			app = (sys::Core*)cs->lpCreateParams;
			return 0;
		}
	}

	if( app )
	{
		return app->MsgProc(msg, wParam, lParam); //Re-call the message loop on our manager instance
	}
	else
	{
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
}
Manager::MsgProc (Member Message Loop)
//MEMBER MESSAGE LOOP
LRESULT WINAPI CALLBACK Manager::MsgProc(UINT msg, WPARAM wParam,
																				   LPARAM lParam)
{
	switch (msg)
	{

	//Handle the message here inside the Manager member function

	}
}


2 Comments

Extracting data from float

Earlier this week i was presented with the simple problem of checking if floating point number was a whole number. I stumbled upon the useful function modf and thought it was worth a quick post. the modf function requires <stdio.h> and <math.h>, and allows you to separate the integral and fractional part of a floating point number.

Taking the value 5.24f as an example…

  • Integral part = 5
  • Fractional part=0.24

modf is fully documented here but is rather simple. modf takes two arguments, the first is the value you wish to query (in the case above this would be 5.24). The second argument is a pointer to where the integral part should be placed. The return value of the method is the fractal part. Therefore the solution to my original problem (testing if a float is infact an integer value) is as follows…

Solution

int f;

if(modf(myValue,&f)==0)
{

//myValue is a whole number

}


Understanding the virtual keyword in C++

The virtual keyword is used to allow for true polymorphism to take place in your c++ application.

A real world example

Let’s create a situation which requires both a base and specialised (derived) class architecture. We will use the real world example of Transport and Car, where Car is derived from transport (as would be a bike, or a plane for that matter). Here are the defenitions for each object

The Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

The Car Object

class Car : public Transport

{

     private:

     public:

     void IdentifyMyself()

     {

          cout << "I am a Car Object" ;

     }

};

Simple enough?

So, lets examine what actually goes on here

1. The Transport class is created as our base class.

2. The Transport class has one private data member.

3. The Transport class has one public method named IdentifyMyself() which outputs a message.

4. The Car object is created as our specialised/derived class.

5. The Car publicly inherits from the base class Transport, obtaining its private data member topSpeed.

6. The Car also defines a public method named IdentifyMyself() which also outputs a message.

What next?

The important part to take from above is that Car inherits from Transport, and that they both contain a defenition for the method IdentifyMyself().

So let’s use our objects! Here is a snippet of code which uses our objects and their methods…

Transport t;

Car c;

t.IdentifyMyself();

c.IdentifyMyself();

Output

I am a Transport ObjectI am a Car object

So, the Car’s method overrides the base class method and the two objects print a different message, simple. Now consider the following….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

We now have a car object as before, but this time we setup a pointer “t” (of the type Transport) to point to our Car, “c” . We are allowed to do so as “Car is a type of Transport”. However, take note of the output.

Output

I am a Car objectI am a Transport object

Even though our pointer “t” points to a Car object, we still call the IdentifyMyself() method of the base class. This is because there is no overriding, and as the pointer is of the type Transport, we simply call the Transport’s method, no longer the one overridden by Car. This is where the virtual keyword comes into play.

Let’s redefine the base class Transport to unclude a virtual method…

The New Transport Object

class Transport

{

     private:

        int topSpeed;

     public:

        virtual void IdentifyMyself()

        {
             cout << "I am a Transport Object";
        }

};

Now lets run the same code again and notice the difference in output….

Test code

Transport* t

Car c;

t=&c;

c.IdentifyMyself();

t->IdentifyMyself();

Output

I am a Car objectI am a Car object

This time when we dereference the pointer “t”,¬† even though our pointer is of the type Transport, due to Transport using the virtual keyword before IdentifyMyself(), it now forces the program to downcast to our inherited object Car and call the overridden IdentifyMyself() method instead.

How does this work under the hood?

Let’s think back to when our Transport class¬† did not employ the virtual keyword. At compile time we can collect up all Transport’s class methods and know where they will reside in memory. However, when we use the virtual keyword, when accessing a pointer to a Transport object, these methods could be anywhere in memory (depending upon the layout of the derived type which overrides them).

The way to resolve this is for each object which uses virtual methods, to keep a vtable (virtual method lookup table) which keeps a list of virtual function pointers. This vtable is always kept at memory offset 0 and can be though of as a hidden datamember for classes which use the virtual keyword or override virtual methods. This can be seen when watching a pointer to our Transport instance, using the Visual Studio Debugger as shown below as __vfptr (virtual function pointers).

This is done automatically by the compiler for any base class which employ virtual methods, and inherently for those that derive from the base class. This vtable is always kept at memory offset 0, so we can always take a pointer to a Transport object, and check its vtable and call the right method. This becomes more complex with multiple inheritence.

Summary

Imagine increasing the scale of this program to include Planes, Trains and Motorbikes. We could now keep a list, 100 items long, of transport pointers…

Transport* mylist[100];

…and iterate through this list, calling ->IdentifyMyself() on each item. Now that the base class implements the virtual keyword, true polymorphism takes place and any derived classes which choose to override this method, get their chance to output a custom message. For those classes that dont override the IdentifyMyself() method, the base class method will be called.