New year, new theme.

After a long time I decided to change the theme of my blog. I had recently changed the name of the blog to Mélange (previously it was called .entrypoint), so I thought it would be good to change the look and feel as well. I was using Classic Beauty, created by esn Studio, for a long time and many people used to tell me that it was a very different one. I liked the simplicity of Classic Beauty, but I think it is time for a change. The new them is Twenty Eleven 1.3 which was created by the WordPress team itself. I love the changing pictures in the header which provides a nice touch to the blog. It also has a light version and a dark version and you can easily switch between the two in the theme options.

Let us see how long before the next change :)

Year twentyTwelve = new Year()

It is that time of the year when you sweep some stuff under the rug and decide that they are a thing of the past. It is also the time when you get the feeling that you need a brand new start. The new year is a time of renewing resolutions, forgiving yourself for your transgressions in the past year and facing the future with recharged batteries and optimism. You get the feeling that this time it will be different, although you are not sure how or why. I love the new year day.

For me, the past few new years also meant writing a blog post with new year resolutions. True to the maxim that history repeats itself, I haven’t completed most of my last year’s new year resolutions. But I did a few, and that is an improvement from the previous year where I did nothing. I had 4 items for 2011:

  1. Reduce my weight – totally failed in this one. I am still the same weight. To look at the bright side – at least that is better than gaining weight :)
  2. Reduce my cholesterol – partial success in this one. I reduced my bad cholesterol by 50 points. I am not where I wanted to be but I am happy that I could achieve at least some success on this.
  3. Study algorithms and data structures – this was a vague goal but I would consider that I have succeeded to some extend in this. Could I learn more ? Of course ! but I know way more than I did same time last year.
  4. Study discrete mathematics – total failure. Didn’t even try.

So basking in the glory of these partial successes and total failures I want to announce this year’s resolutions:

  1. Reduce my weight by 15 lbs.
  2. Bring my cholesterol to normal level.
  3. Increase my knowledge of algorithms and data structures. This will be like part 2 of my resolution of 2011. As part of this I will be taking the design and analysis online class from Stanford.
  4. Write at least 12 blog posts. One per month on average. This is the first one.
  5. Increase my volleyball skills. I have registered for a volleyball clinic with my friends and I hope that will help me improve my skills. Also reducing my weight should help me jump higher which will allow me to play better.

That is it, five items to get done in 2012.

Looking back at 2011, I think it was a good year for me.

I have always wanted to learn and work in C++ and to that end I changed teams at work. I am quite proud to say that I am quite comfortable with C++ now. I am by no means an expert but I am not afraid of C++ now.

On the personal side my wife and I visited quite a few places this year. In spring we visited some places in Washington and Oregon. In summer we went to Las Vegas and the Grand Canyon. In fall we toured Washington DC, New York city and Niagara. We had a chance to meet our old friend Ranjeesh and his family while we were at Washington DC and we had a great time together. After Christmas we spent a few days driving along the Oregon coastal area. I immensely enjoyed these trips and I am sure I will always have fond memories of those trips that we made.

We also shifted apartments from Redmond to Issaquah. Initially it was quite difficult and we missed Redmond terribly, but now we love Issaquah. We still miss Redmond but Issaquah is a very nice place to live and closer to work as well.

I guess that is it. Good bye 2011. Welcome 2012.

I wish you, my dear reader, a wonderful and joyous new year !

RAII – Resource Acquisition Is Initialization

Resource Acquisition Is Initialization (RAII) is a programming idiom used in C++ for resource management. To understand it clearly let us look at a common programming problem.

Consider a method that needs to be synchronized across multiple threads. If you were programming against Win32 and if you were using Critical Sections as your synchronization primitive, you would call EnterCriticalSection at the beginning of the method and call LeaveCriticalSection at the end.

void DoStuff()
{
EnterCriticalSection(_pcs);

/* Code that should accessed only by one thread at a time. */

LeaveCriticalSection(_pcs);
}

There are two major drawbacks to this approach.

The first is that the programmer might forget to call LeaveCriticalSection at the end of the code. The chances of this happening increases when there are multiple exit points in the function. Even if you take care to exit at a single point and do the resource cleanup it is possible that somebody maintaining your code several years later might add an exit point in the middle of the function thereby missing cleanup. While code reviews will help alleviate this problem to some extend I have personally seen this happening in code that was reviewed by multiple people, unit tested and checked in.

The second problem with manually allocating and cleaning up resources is exceptions. Unless you handle the exception and do cleanup in the exception handler, you will leak your resource. In C++ exceptions are not idiomatic and you rarely see exception handlers. Even though your code itself might not throw exceptions the code that you call into might throw exceptions (for example a third party library). Most implementations nowadays When an exception is thrown after you acquired a resource but before your cleanup code is executed, your resource is now leaked. If we consider the example I mentioned above, your code has now acquired a thread synchronization primitive but never released it. There is a chance you will have a thread waiting forever. That may mean an unresponsive UI and an unhappy customer.

RAII solves this problem. RAII depends on three C++ features – constructors, destructors and the ability to create objects on the stack. The constructor of a class is invoked when an instance of the class is created. The destructor of a class is invoked when the instance is deleted. Objects created on the stack are automatically deleted when it goes out of scope.

This is how we use RAII to solve our problem:

  • We need a class whose purpose is to manage the resource. In the example above, the resource is the critical section. Let us create a class named Lock to manage the critical section.
  • An instance of the resource manager should be created on the stack.
  • The resource is initialized in the constructor of the resource manager. So, in our example, we call EnterCriticalSection() in the constructor of the Lock class.
  • We add the code that use the resource. In our case, we add the code that needs to be synchronized between multiple threads.
  • The resource is cleaned up in the destructor. Since the object is on the stack, the object is deleted when the function exits and the stack unwinds. In our example, we call LeaveCriticalSection() in the destructor of the Lock class.
// Manages a critical section. class Lock
{
public:
    Lock(PCRITICAL_SECTION pcs) : _pcs(pcs)
    {
        // Initialize resource in the constructor. EnterCriticalSection(_pcs);
    }

    ~Lock()
    {
        // Release resource in the destructor. LeaveCriticalSection(_pcs);
    }

private:
    PCRITICAL_SECTION _pcs;
};

Now the DoStuff() method can be re-written as follows:

void DoStuff()
{
    Lock lock(_pcs); /* Create the resource manager on the stack */

    /* Code that should accessed only by one thread at a time. */
 /* Critical section automatically released when function returns. */ 
}

Of course this can be wasteful only if a small part of the code needs to be synchronized. The way it is implemented above, the whole function is synchronized. We can get around this limitation by creating a new scope and using the lock only inside that scope.

void DoStuff()
{
    /* Code that need not be synchronized. */ 
   { // Start new scope. 
        Lock lock(_pcs);

        /* Code that should accessed only by one thread at a time. */ 

   } // End of the scope. lock is destroyed and crtical section is released. 

 /* More code that need not be synchronized. */ 
}

That is it folks. Guaranteed cleanup using RAII.

What I miss about C#

It has been a month or so since I started programming in C++. To be frank it is not the monster that I thought it would be and it wasn’t that hard to move to C++ from C#. Granted I haven’t faced any of the notorious and nasty bugs that is difficult to debug in native code but I still think C++ isn’t as hard as I thought it would be (touch wood).

That being said I do miss a few things that I was used to in C# and .NET. Here are the top 3:

  1. Refactoring tools
  2. Garbage collection
  3. A good mocking framework for unit testing

Coming Home

C++ was my first programming language. We were “taught” C++ in our first semester for our Engineering curriculum. Needless to say it was a nightmare. C++ is too big and too hard as a first programming language. At least it was for me. I didn’t own a computer at that time and I hadn’t really programmed before. So I really struggled in that class. For once I was happy that I didn’t get a seat for Computer Science for my undergraduate studies. The teacher was clueless and the students even more. There were a few students who had studied C++ or some other programming language before and they managed to help us with the assignments and stuff. I barely made the pass mark in the final exam. With all that struggle C++ left some lasting scars.

My professional life as a programmer (Programmer sounds a little lowly, maybe I should say Software Engineer) I started with Visual Basic and then moved to C#. Nine years passed and I was still scared of having to program in C++. But some time back I decided that I should conquer my fear of C++. I moved teams and joined a team that uses C++, COM, ATL and other stuff that scares the shit out of the ordinary programmers. I think I have got my feet wet now and you know what, I believe I can do it. I will share my learning experiences here. And you lucky fellow wayfarer, you will get to read it all – imagine all that reading pleasure – for free. When you read about adjustor thunks and single threaded apartments you might even get a small orgasm. Well, unless I find C++ too hard for me to handle and join another team that use Visual Basic.

Creating a Windows Service in Visual Studio

In earlier versions of Visual Studio there was a template to create Windows Service in C++ by going to File menu -> New and clicking on Project. In the New Project dialog, if we click the Visual C++ Projects node in the Project Types pane, there was a Window Service template. This is not available in Visual Studio 2010. The C++/CLI template for creating Windows Services was also removed. Only the C# template is available if you want to use managed code to develop Windows Services. If you need to create a Windows Service in unmanaged C++, your option is to use ATL.

In the new Project dialog, under Visual C++, click on ATL and select ATL Project in the center pane. Enter the name of the project and click Ok button.

 

This displays the ATL Project Wizard. Click on the Next button.

 

In the Application Settings, select Service (EXE) as the Application type and click Finish. Now Visual Studio will generate the required code files to get you started on developing a Windows Service.

 

However, there is one gotcha.

When you build the solution that you just created you will (most probably) get an error:

Error    1    error MSB3073: The command “”<path to Atl.Service.exe>” /RegServer :VCEnd” exited with code -2147024891.    C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets    113    6    Atl.Service

Not a very useful error message. And I was a little confused because I was building the template created by Visual Studio, I didn’t make any modifications to it. Was Visual Studio shipping templates that won’t compile ? It turns out that the problem was that Visual Studio was not running as an administrator. Once you close Visual Studio and restart it to run as an Administrator, you will not the see this problem anymore. The project will build fine.

Happy coding.

 

Free online course on Artificial Intelligence conducted by Stanford

Stanford is conducting a free online course on Artificial Intelligence taught by none other than Peter Norvig and Sebastian Thrun. There are 2 tracks – basic and advanced. If you don’t have time for the assignments and exams take the basic track. You can switch between the tracks any time. You will receive a statement of accomplishment signed by Sebastian Thrun and Peter Norvig.

The course is from Oct 10th to Dec 18th.

Here is the website for the course. Course overview is here. You can enroll here. Course schedule is here.

Welcome 2011

I have had quite a few resolutions for 2010. Now I hold my head high and tell you all – I didn’t do even one of them :)

While that speaks volumes about my nature, I wouldn’t want you to think I am quitter. I have more resolutions for this year.

  • I will reduce my weight by 15 lbs. I weigh 185 lbs now, so by Dec 2011 I expect to be 170 lbs. I haven’t been 170 lbs since some time in 2002. Now I expect to be back at that weight by 2012.
  • I will reduce my cholesterol to normal values. Now I am grossly over the normal values (total cholesterol = 300)
  • I will greatly increase my knowledge on algorithms and data-structures. This is a vague one. But that’s OK. Any progress in this direction is good for me.
  • I will study discrete mathematics. This is also quite vague but my intention is to be a little less clueless than I am now.

That is it friends. Just 4 things. Let us see how that goes.

A Learning Project

Binil and I have decided to study Computer Systems: A Programmer’s Perspective together. We are going to use the first edition because we both already own that and the 2nd edition is damn costly. Binil is in California and I am in Washington, so it is going to be a long distance combined study. We imagine this would take up the rest of this year, and even then it will be a challenging task (because we intend to do the exercises as well).

One of the challenge would be to maintain the interest in the project. I usually lose interest in any book after reading about 100 pages or so and this book is a little over 900 pages. We have decided that one should help the other maintain the momentum, motivation and interest. Another challenge is that (as I mentioned earlier) we are not in the same location. We decided we would communicate through email during the weekdays and have a telecon on the weekends. We should be able to fine tune the process as we go along. We also expect other challenges to show up as we go along but failing halfway would be better than not doing it at all (this pearl of wisdom may not apply to everything, so reader discretion advised).

For the first week, starting today, we will attempt to read the first chapter (there are no exercises in the first chapter).

P.S. One of the reasons for making this blog post is that making our commitments public will give us more motivation and inspiration to complete it or at least stick with it for a longer period than otherwise.

Slow down or pay up

As I was driving to office today I noticed a message on the freeway warning board – “Slow down or pay up”. I find these warnings tasteless. The tone is offensive, just like the more frequently seen “Click It or Ticket”. That tone might works for kids but with adults I can imagine the response to such warnings to be “Fuck You”. In my opinion something more appropriate would “Please slow down for your own safety” or “Please slow down for the sake of everybody”.

P.S. I am not against keeping the speed within limits on the road, I am just saying that the message should be friendly. I could be wrong in my assessment because the “Click It or Ticket” is America’s most successful seat belt enforcement campaign creating a seat belt usage of 83%. On an unrelated note, 58.7% of statistics are made up on the spot.