Worker Threads

Introduction

Worker threads are an elegant solution to a number of problems about concurrent processing; for example, the need to keep the GUI active while a computation is being performed. This essay addresses some of the issues of using worker threads. A companion essay talks about some techniques dealing with user-interface threads.

Why Worker Threads?

Consider a simple implementation of a program. For our purposes, the program has the task of inverting the color of every pixel of an image, just because we sometimes need a concrete example to illustrate techniques. For the sake of our example, we will assume that the image being processed is 10 megapixels of 24-bit color.

The GUI has a menu item or other means of saying "Invert it now". This calls the doInvert method on the view class:

void CMyView::doInvert()
    {
     for(int x=y = 0; y < image.height; y++)
          for(int x = 0; x < image.width; x++)
              changePixel(x, y);
    }

This is a perfectly correct program. It traverses all 10 megapixels, happily changing the pixels, until it completes. But it is not a good implementation.

Why not? Because the entire GUI is dead until the operation completes. This means that for some long duration, the user is forced to wait while the operation proceeds, and there is absolutely nothing that can be done about it. If the user decides that the transformation is bogus, and wants to stop it, well, tough. It is going to complete anyway.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone” - Bjarne Stroustrup