Easy Multithreading in ATL Windows Applications

At my work, I’m the GUI developer. Our application implies a lot of computations to do. The end user is expected to watch some Flash clips until the work is done.

I chose the ATL GUI framework. Because I’m too lazy to constantly call the Win API‘s functions, I created the C++ template class to do this job for me. Then, I decided that the code I wrote could be extremely helpful when creating any ATL GUI applications.

The idea is to exploit the old-school windows messages to notify the owner window that the job is done. I know this idea sounds too complicated when programming in pure Win32, but it can be implemented with just a few lines of C++ code when using ATL windows classes. I also exploited the useful yet poorly understood C++ language feature—pointers to C++ member functions.

Using this class is extremely simple. Just add Async.h to your project, inherit your main window class from the CAsync<CMyWindowWindowClass>, add the CHAIN_MSG_MAP macro to the window’s message map, and you are ready to execute your class functions asynchronously.

In the attachment, you’ll find the demo project. I wrote and debugged this simple application while chilling out at home just to demonstrate the possible use for this technique. That’s why the application only moves the progress bar, not actually doing any useful work. I tried to comment the code well to make it easier to read and understand.

Pros

Easy to use. Good for any network clients. No WIN32 Wait functions. Readable C++ code.

Cons

Can’t terminate hung jobs (could be implemented easily). Suitable only for GUI applications because it depends on window messages. Can only pass one or more Variant values to the thread (however, you may use any data stored in your class data members). Besides, you should think about the lifetime of the thread and the window object: If the window object is destroyed but the application is still active and some thread[s] are active, you’ll most likely get an access violation when accessing the class members from the thread.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read