Wednesday, March 5, 2008

new never returns NULL

Recently I gave the Brainbench c++ test and came across an interesting question.

It was something like:

{
int *i = new int[10];
if(!i)
{
NoMemoryHandler();
}
}


In this question, the right answer is "NoMemoryHandler() is never called".

Thats because, in c++ new operator never returns a NULL. In case of failure new simply throws an exception std::bad_alloc.

Now if you catch the exception and handle the situation, then its fine. Otherwise, if you don't catch the exception, your lovely program will get terminated. (Thats so uncool!)

Now everytime whenever you gotta write code, it should be like:

{
try
{
int *i = new int[10];
}
catch(bad_alloc &e)
{
cout << "OK, new failed!! But on the positive side, I am aware of it !!" << endl;
}
}

Fortunately to our rescue there is another version of new which doesn't throw anything on failing.

With reference to GCC's online docs we come to know about the nothrow version of new.

{
int *i = new (nothrow) int[10];
if(!i)
{
cout << "new failed!! but now I am not a slave of exceptions !!" << endl;
}
}

When I use the standard version of new, I have to handle the exception it throws on failure, else my program gets terminated.
If I use the "nothrow" version of new, I still need to write some healing code, but then I am free of unnecessary try{} and catch(){} blocks.

Until and unless I have to customize "new" for specific needs, I would always prefer the "nothrow" verison.

-----------------------------------------------------------------------
And yeah... I got a 4.69 score. Transcript id: 7416277.

Sunday, March 2, 2008

Thread Pool implementation using c++

I was browsing through some Design Patterns over the internet, and I recently came across the Thread Pool pattern. My natural reaction was to google around for some implementations.

I liked Blake Thompson's win32 implementation on Intel's website. Inspired from it, I thought of writing an implementation for unix/linux platform.

ThreadPool class manages all the ThreadPool related activities. This includes keeping track of idle threads and synchronizations between all threads.

ThreadPool class uses a WorkerThread class.

Now this WorkerThread is having a virtual function executeThis().
The user needs to subclass WorkerThread and implement executeThis() to assign the tasks.

You can download the code and documentation from http://code.google.com/p/cppthreadpool/
This code is licensed under GPL v3. So feel free to use it, modify it, and whatever it.

I have currently tested it under cygwin environment, but I am expecting it to work in unix and linux environments as well (since it uses POSIX threads). It will be great if someone with unix/linux environment can test it.

If you have any doubts about how to use this Thread Pool implementation, then please feel free to ask me at shobhitgupta12@gmail.com