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:

Int
WINAPI
WinMain(
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:

  • #define MB_ICONWARNING MB_ICONEXCLAMATION
  • #define MB_ICONERROR MB_ICONHAND
  • #define MB_ICONINFORMATION MB_ICONASTERISK
  • #define MB_ICONSTOP MB_ICONHAND

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);
grp.add_thread(p);
// do something…
grp.remove_thread(p)

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);
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.

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690

 

Solution:


#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;
myRead.open(“data.dat”);
int x;
while (!myRead.eof())
{
myRead >> x;
newVector.push_back(x);
}
myRead.close();
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