Worker Threads

The thread solution

It is almost always the case that you can use threads to do the job more easily. This is not without certain costs and hazards, but it ultimately is the better method.

Here's a solution to handling the invert-everything. Note that we have to move from the pure-C domain (which we interface to via a static method) to the MFC domain.

To the class (in this example, a CView-derived class), add the following declarations:

static UINT run(LPVOID p);
void run();
volatile BOOL running;

To start a thread, your handler does

void CMyView::doInvert()
     running = TRUE;
     AfxBeginThread(run, this);
UINT CMyView::run(LPVOID p)
     CMyView * me = (CMyView *)p;
     return 0;
void CMyView::run()
     for(int x=y = 0; running && y < image.height; y++)
          for(int x = 0; running && x < image.width; x++)
              changePixel(x, y);
    running = FALSE;

The command to stop the thread is very simple:

void CMyView::OnStop()
    running = FALSE;

That's all there is to it!

Well, almost. Keep reading.

For example, the above code assumes that the thread will not try to access any member variables of the view unless it is certain they exist. This includes handles to synchronization primitives or pointers to a CRITICAL_SECTION that might be used to synchronize interactions between the thread and its view. This requires a more graceful shutdown mechanism.

Note that the declaration of the running variable includes the modifier volatile. This is because under certain optimizations, the compiler will discover that in the body of the loop there is absolutely nothing that changes the running flag, and therefore, cleverly, it can avoid testing it each time through the loop. This means that although you change the value in another thread, the change is never seen. By adding the volatile modifier, you tell the compiler that it cannot assume the variable will remain unmodified during the execution of the loop, even though there is no code in the loop that can change the variable.

You might also like...



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.

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann