Jun 7, 2011

The Easy Way to Start a Task

DRY – Don't Repeat Yourself

Every NetBurner project I have ever done has had at least one task in addition to the main task. Every time you create a task there are a number of repetitive steps you have to do, assign a unique priority, create and assign a proper stack, provide a main event loop and if it's a class member you have to go through special steps to point to that method.

Wouldn't it be nice if you could fire up a task by just inheriting from a Task class? Then you just write the code you want the task to execute and you're done. Isn't that what OOP is all about? Well, since you were smart enough to program for a NetBurner you can.  Even if you use another embedded platform with a C++ compiler, adapting this class should prove to be very easy. Here's an example of a complete class that runs in a separate task with a default stack and a default (but always valid) priority.

Odds are good that in your class you want to put something a wee bit more useful than just an OSTimeDly() call. To use this class you create an instance of it and call Startup() on it like this:

SomeConcreteTask myTask;

That's it, you just call Startup() and the Initialize() method will be running in a separate task. TaskBase does more than this of course. You can modify the stack size and priority if you want. It even tries to handle shutting down gracefully, but you should read the unit tests and code to see the proper method.

The only requirement for any task inheriting from TaskBase is that it has to implement the pure virtual function Initialize().

The only thing you need is my TaskBase class source code, so I put it up on GistHub.  I think this class is pretty much uncoupled from the rest of my library except for the calls to DebugUtil::. Those are safe to remove. It will give you something to do as you read through the code. The .cpp and .h files combined are about 300 lines in total (including blank and comment lines). It won't take anyone nearly as long to read as it took me to write. The third file is for documentation only and is the body of the unit test .cpp file. Without my testing framework (which was uploaded in the projects area of the NetBurner forum) you can't compile this, but you can still read it to see how the various features of the class are used.  If anyone does download this and finds ways to improve it, it would be greatly appreciated if you either forward on suggestions to me or fork and update the gist.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.