Monthly Archives: May 2013

Multithreading and the C Type System | Introduction | InformIT

Multithreading and the C Type System | Introduction | InformIT.


“The Best Programming Advice I Ever Got” with Andrei Alexandrescu | | InformIT

“The Best Programming Advice I Ever Got” with Andrei Alexandrescu | | InformIT.

learning how to learn is more important than learning anything else….

Windows API Programming using C/C++

English: .NET Stack and Win32/64 API comparison.

English: .NET Stack and Win32/64 API comparison. (Photo credit: Wikipedia)

Windows Operating system is undoubtedly has a major market share of desktop and laptop machines. Referring to Wikipedia, it is about 80% of the PC machines running one of the many versions of Windows.   Here I am not going to discuss the pros and cons of using Windows over other available OS choices but I only want to emphasize that knowing how to program applications for Windows can give a major boost to your career growth.

There are many available options for programming windows application. Keeping Windows 8 metro style application apart, all other versions of windows and even Windows 8 desktop side mainly rely on Windows API. (Though Windows RT underneath of Windows 8 metro style (or window store) apps is also based on Windows API).

You will normally found two terms used for Windows API, win32 and win64 for Windows 32 bit architecture and Windows 64 bit architecture. But the difference is so minute as far as programming is concerned that if you knew one, you already know the other.  One of the basic differences is the pointer address space which is 64 bit in case of Win64 API which means you can access 8 terabyte of memory, at least in theory.

We have found many wrapper frameworks of Windows API, like MFC (Microsoft Foundation Classes) and the famous .Net. But let me tell you these all are just wrappers of windows API in effort to simplify and increase productivity. But these frameworks also come with some costs, in terms of efficiency and control. Folks, who knew C/C++ and any other managed language as well, will understand what I am trying to say here.

If you want to learn any of these wrapper frameworks, it is a good idea to have a feel of Windows API to know and learn how Windows operating system internally works. Windows API exposes lowest level of operating system functionality and gives you complete control and power.

With this little motivation, I will try to show you and gives you a feel of Windows API programming using C and C++ with a serious of articles. I am not calling these articles as tutorials because these are not merely tutorials but I will try to take a little deeper dive into Windows API.

I will start with the legendry very first program of any computer programming language, the “Hello World” program. I will show you each line of code and then explain it in a little detail and at the end you can find the complete code in one place, which you can copy and paste and run.

I am assuming that you people already understand C/C++ syntax and have experience in console application programming. So I am not going to explain C/C++ syntax, what a header file is, what classes in case of C++ are and how to compile your code. I will focus just on Win API.

A minor point can be noted here that many or I would say all Windows programs and Win API use a system called “Hungarian notation” for naming variables. This system involves prefacing the variable name with a short prefix that indicates the variable’s data type. I’ll discuss this concept later in detail.

Hello World – Win API version using C/C++”

#include <windows.h>

It begins by including a header file that you will find at the top of every Win API program written in C or C++.

WINDOWS.H is a master header file which includes many other Win API header files, some of those include many other header files as well. The most important basic of these header files are stated below:

  • WINDEF.H                      it has basic type definitions.
  • WINNT.H                        it has type definitions for Unicode support.
  • WINBASE.H                  it has kernel functions.
  • WINUSER.H                 it has user interface functions.
  • WINGDI.H                     it has graphics device interface functions.

These header files have definations of all the Windows data types, function calls, data structures, and constant identifiers. These are an important part of Windows documentation and opening one of them and trying to understand it is really a good idea for learning more about windows API.

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow)

As every C/C++ program has an entry point, a windows program also has an entry point. In case of windows program, it is WinMain instead of main of C/C++. It is declared in WINBASE.H as below:

HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd

Return type is int and The WINAPI identifier is defined in WINDEF.H with the statement:

#define WINAPI __stdcall

This statement specifies a calling convention that involves how machine code is generated to place function call arguments on the stack. Most Windows function calls are declared as WINAPI.

The first parameter to WinMain is something called an “instance handle.” In Windows programming, a handle is simply a number that an application uses to identify something. Do not confuse it with pointer as it is not a pointer. In this case, the handle uniquely identifies the program. It is required as an argument to some other Windows function calls.

The second parameter: In early versions of Windows, when you ran the same program concurrently more than once, you created multiple instances of that program. All instances of the same application shared code and read−only memory (usually resources such as menu and dialog box templates). A program could determine if other instances of itself were running by checking the hPrevInstance parameter. It could then skip certain chores and move some data from the previous instance into its own data area. In the 32bit and 64bit versions of Windows, this concept has been abandoned. The second parameter to WinMain is always NULL (defined as 0).

The third parameter to WinMain is the command line used to run the program. Some Windows applications use this to load a file into memory when the program is started. It is not relevant here. The variable type LPSTR can be read as Long Pointer to String. It is a heritage of 16bit windows where pointers were 16bit and use segment/offset addressing scheme. We can use the same safely with 32bit and 64bit versions of Windows. We can also use PSTR which is simply a pointer to string or can use Char * in its place.

The fourth parameter to WinMain indicates how the program should be initially displayed either normally or maximized to fill the window, or minimized to be displayed in the task list bar. We’ll see how this parameter is used later on.

The one and only line of WinMain would be as follows,

MessageBox (NULL, "Welcome to Windows Programming", "Welcome Message", 0) ;

The MessageBox function is designed to display short messages. The little window that MessageBox displays is actually considered to be a dialog box, we used to see in almost every session of Windows we run.

The first argument to MessageBox is normally a window handle. We’ll see what this means later. The second argument is the text string that appears in the body of the message box, and the third argument is the text string that appears in the caption bar of the message box.

The fourth argument to MessageBox can be a combination of constants beginning with the prefix MB_ that are defined in WINUSER.H. You can pick one constant from the first set to indicate what buttons you wish to appear in the dialog box:

  • #define MB_OK                                                              0x00000000L
  • #define MB_OKCANCEL                                              0x00000001L
  • #define MB_ABORTRETRYIGNORE                        0x00000002L
  • #define MB_YESNOCANCEL                                      0x00000003L
  • #define MB_YESNO                                                     0x00000004L
  • #define MB_RETRYCANCEL                                    0x00000005L

When you set the fourth argument to 0 in this function call, only the OK button appears. You can use the C (|) operator to combine one of the constants shown above with a constant that indicates which of the buttons is the default:

  • #define MB_DEFBUTTON1                          0x00000000L
  • #define MB_DEFBUTTON2                          0x00000100L
  • #define MB_DEFBUTTON3                          0x00000200L
  • #define MB_DEFBUTTON4                          0x00000300L

You can also use a constant that indicates the appearance of an icon in the message box:

  • #define MB_ICONHAND                              0x00000010L
  • #define MB_ICONQUESTION                     0x00000020L
  • #define MB_ICONEXCLAMATION            0x00000030L
  • #define MB_ICONASTERISK                        0x00000040L

Some of these icons have alternate names:


There are a few other MB_ constants, but you can consult the header file yourself or in the documentation.

In this program, the MessageBox function returns the value 1, but it’s more proper to say that it returns IDOK, which is defined in WINUSER.H as equaling 1. Depending on the other buttons present in the message box, the MessageBox function can also return IDYES, IDNO, IDCANCEL, IDABORT, IDRETRY, or IDIGNORE.

Now below is the complete code of your very first Windows program which you can copy/paste or type in your favorite C/C++ IDE, compile and run.

#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
MessageBox (NULL, "Welcome to Windows Programming", "Welcome Message", 0) ;
return 0 ;

Experiment by your own is the key of learning and I will get back to you with next article on Windows API very soon.

Fragments taken from Charles Petzold – programming Windows

Creating a Thread using C++ Boost Lib.

Creating a thread is deceptively simple. All you have to do is create a thread object on the stack or the heap, and pass it a functor that tells it where it can begin working. For this discussion, a “thread” is actually two things. First, it’s an object of the class thread, which is a C++ object in the conventional sense. When I am referring to this object, I will say “thread object.” Then there is the thread of execution, which is an operating system thread that is represented by the thread object. When I say “thread” , I mean the operating system thread. Let’s get right to the code in the example. The thread constructor takes a functor (or function pointer) that takes no arguments and returns void. Look at this line from below code,

boost::thread myThread(threadFun);
This creates the myThread object on the stack, which represents a new operating system thread that begins executing threadFun. At that point, the code in threadFun and the code in main are, at least in theory, running in parallel. They may not exactly be running in parallel, of course, because your machine may have only one processor, in which case this is impossible (recent processor architectures have made this not quite true, but I’ll ignore dual-core or above processors and the like for now). If you have only one processor, then the operating system will give each thread you create a slice of time in the run state before it is suspended. Because these slices of time can be of varying sizes, you can never be guaranteed which thread will reach a particular point first.
This is the aspect of multithreaded programming that makes it difficult: multithreaded program state is nondeterministic. The same multithreaded program, run multiple times, with the same inputs, can produce different output. Coordinating resources used by multiple threads is the subject of my next post.
After creating myThread, the main thread continues, at least for a moment, until it reaches the next line:
boost::thread::yield( );
This puts the current thread (in this case the main thread) in a sleep state, which means the operating system will switch to another thread or another process using some operating-system-specific policy. yield is a way of telling the operating system that the current thread wants to give up the rest of its slice of time. Meanwhile, the newthread is executing threadFun. When threadFun is done, the child thread goes away. Note that the thread object doesn’t go away, because it’s still a C++ object that’s in scope. This is an important distinction.
The thread object is something that exists on the heap or the stack, and works just like any other C++ object. When the calling code exits scope, any stack thread objects are destroyed and, alternatively, when the caller calls delete on a thread*, the corresponding heap thread object disappears. But thread objects are just proxies for the actual operating system threads, and when they are destroyed the operating system threads aren’t guaranteed to go away. They merely become detached, meaning that they cannot later be rejoined. This is not a bad thing. Threads use resources, and in any (well-designed) multithreaded application, access to such resources (objects, sockets, files, rawmemory, and so on) is controlled with mutexes, which are objects used for serializing access to something among multiple threads.

If an operating system thread is killed, it will not release its locks or deallocate its resources, similarly to how killing a process does not give it a chance to flush its buffers or release operating system resources properly. Simply ending a thread when you think it ought to be finished is like pulling a ladder out from under a painter when his time is up.
Thus, we have the join member function. As in below code, you can call join to wait for a child thread to finish. join is a polite way of telling the thread that you are going to wait until it’s done working:
myThread.join( );
The thread that calls join goes into a wait state until the thread represented by myThread is finished. If it never finishes, join never returns. join is the best way to wait for a child thread to finish. You may notice that if you put something meaningful in threadFun, but comment out the use of join, the thread doesn’t finish its work. Try this out by putting a loop or some long operation in threadFun. This is because when the operating system destroys a process, all of its child threads go with it, whether they’re done or not. Without the call to join, main doesn’t wait for its child thread: it exits, and the operating system thread is destroyed.

If you need to create several threads, consider grouping them with a thread_group object. A thread_group object can manage threads in a couple of ways. First, you can call add_thread with a pointer to a thread object, and that object will be added to the group. Here’s a sample:
boost::thread_group grp;
boost::thread* p = new boost::thread(threadFun);
// do something…

When grp’s destructor is called, it will delete each of the thread pointers that were added with add_thread. For this reason, you can only add pointers to heap thread objects to a thread_group. Remove a thread by calling remove_thread and passing in the thread object’s address (remove_thread finds the corresponding thread object in the group by comparing the pointer values, not by comparing the objects they point to). remove_thread will remove the pointer to that thread from the group, but you are still responsible for delete-ing it. You can also add a thread to a group without having to create it yourself by calling create_thread, which (like a thread object) takes a functor as an argument and begins executing it in a new operating system thread. For example, to spawn two threads in a group, do this:
boost::thread_group grp;
grp.create_thread(threadFun); // Now there are two threads in grp
grp.join_all( ); // Wait for all threads to finish
Whether you add threads to the group with create_thread or add_thread, you can call join_all to wait for all of the threads in the group to complete. Calling join_all is the same as calling join on each of the threads in the group: when all of the threads in the group have completed their work join_all returns.
Creating a thread object allows a separate thread of execution to begin. Doing it with the Boost Threads library is deceptively easy, though, so design carefully.

#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
struct MyThreadFunc

void operator( )( )

// Do something long-running...
} threadFun;
int main( )

boost::thread myThread(threadFun); // Create a thread that starts
// running threadFun

boost::thread::yield( ); // Give up the main thread's timeslice
// so the child thread can get some work
// done.
// Go do some other work...
myThread.join( ); // The current (i.e., main) thread will wait
// for myThread to finish before it returns



Project Euler Problem#13 solution in C++

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.




#include <stdio.h>
#include <iostream>
#include "projectEulerProblem13.h" //data is stored in char data[100][51] in this file.

int main ()
int x, y, columnSum[50], carry = 0;

for (x = 49; x >= 0; x--)
columnSum[x] = carry;
for (y = 0; y < 100; y++)
columnSum[x] += (int)data[y][x] - 48;

carry = columnSum[x] / 10;

std::cout << carry << std::endl;

for (x = 0; x < 50; x++)
std::cout << (columnSum[x] % 10) << std::endl;

return 0;


Some advice for college freshmen

I don’t know the author but this seems a very good advise for fresh Graduates.

Strong skill of one or more good languages like C++, Java and C#:

Must have strong skills with control structures. Don’t mess up if you’re asked to print out triangle or other shaped piles of ‘x’s with loops.
Must have strong skills with recursion. You must know how to transform a looped task into a recursive one and vice versa, for example: multiplication using addition recursively.
If your language is C/C++, you must know how to play with pointers and references.
Understand pass by value and reference.
Clearly understand scopes and memory allocation, de-allocation. Know when an object is destroyed and when to destroy.
Know the usage of all operators including bit-wise ones.
In-depth knowledge of OOP:
Only being able to write classes and doing encapsulation and inheritance is not what you should call good OOP.
Clearly understand how function overloading, overriding, polymorphism works.
Clearly understand how constructor/destructor (if any) works with inheritance.
Clearly know the difference and use of Interfaces and Abstract classes.
Know how to overload operators. Why and how copy constructor is defined/used.
Know common data structures:
At least know the common data structures like stack, queue, linked list, doubly linked list (know circular version of all of them) and trees.
Be a skilled implementer of any of those, have clear concept of how push, pop, add, delete, peek etc method works on those data structures.
Know most common algorithms well:
You don’t need to memorize pseudo codes line by line but you need to have clear concept of most common algorithms of sorting(bubble, quick, merge, heap, bucket, etc), searching (including DFS, BFS), etc.
As a fresher you must know their time and space complexities, pitfalls and improvements (if any).
General computing concepts:
Know processes and threads, how are they related to each other, how to program them, etc.
Understand TCP/IP: Don’t think it’s only the network administrator’s task to understand TCP/IP. All programmers ever doing any network or web programming should have clear TCP/IP concepts and understanding.
Be skilled in debugging in IDEs:
Be skilled in any of Visual Studio/Visual Studio.Net, Eclipse, Netbeans, KDevelop, etc.
Know how to debug your code.
Have basic knowledge of Software Engineering and SDLC.

General Advise:
Start with C++ or Java, avoid starting with scripting languages:
If you’re learning programming for the first time, avoid starting with scripting or loosely typed languages like: PHP, ASP, Perl, etc or Visual Basic. It may destroy your understanding of program execution, data types, memory allocation, etc.
Start with C++ or Java. If you want to me to be specific, start with C++, you’ll love it for the rest of your life.. 🙂 It’ll be easier for you to learn (almost) any other language (like: C#, PHP, ASP, etc).
If you ask, do you need to know C to start with C++? Or should you learn C first and then C++? C definitely helps a lot for learning C++ but it’s not mandatory to start with C.
If you want to be a good programmer, keep on coding at least 20 hours a week for the next 4 years :). Never stop learning new technologies that are coming out everyday. Know some of the many languages/technologies but be master of one. Know at least one language very well.

Write Random Numbers to a File and Read Into Vector in C++

Graham's Code

// Programmer: Graham Nedelka
// Output random numbers to file, read in via vector
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
using namespace std;
int main () {
srand (time(NULL));
ofstream myFile(“data.dat”);
for (int i = 0; i < 1000000; i++)
myFile << rand() % 10000 + 1 << endl;
vector<int> newVector;
ifstream myRead;“data.dat”);
int x;
while (!myRead.eof())
myRead >> x;
for (int i = 0; i < newVector.size(); i++)
cout << newVector[i] << endl;
sort(newVector.begin(), newVector.end());
for (int i = 0; i < newVector.size(); i++)
cout << newVector[i] << endl;
return 0;

View original post

A general method to multiply matrices

C++ | Area of different shapes using function

Agile software development – get back to basics to make it work

Altabel Group's Blog

For some years, Agile methodologies have been widely adopted within the information technology software world to bring new products and services to market quickly and efficiently, increasingly taking over from more traditional approaches such as ‘waterfall’. While it may have promised much, Agile has not been without its critics, who say that it does not live up to expectations, that users can become too bogged down in the processes and lose sight of the end goal. They also fear Agile projects become siloed into teams, rather than being visible to the organisation as a whole.

However, as an increasing number of companies are finding, Agile CAN deliver on expectations, if some simple principles are followed: what might be called “pragmatic agile”. Supporting tools also have a role, such as SCM (software configuration management). SCM can help ensure that a project remains visible to all the key stakeholders, while supporting Agile-related…

View original post 1,363 more words