Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Defining Tasks

A thread carries out a task, so you need a way to describe that task. The Runnable class provides a common interface to execute any arbitrary task. Here is the core of the ZThread Runnable class, which you will find in Runnable.h in the include directory, after installing the ZThread library:

class Runnable {
virtual void run() = 0;
virtual ~Runnable() {}

By making this an abstract base class, Runnable is easily combinable with a base class and other classes.

To define a task, simply inherit from the Runnable class and override run( ) to make the task do your bidding.

For example, the following LiftOff task displays the countdown before liftoff:

//: C11:LiftOff.h
// Demonstration of the Runnable interface.
#ifndef LIFTOFF_H
#define LIFTOFF_H
#include <iostream>
#include "zthread/Runnable.h"
class LiftOff : public ZThread::Runnable {
int countDown;
int id;
LiftOff(int count, int ident = 0) :
countDown(count), id(ident) {}
~LiftOff() {
std::cout << id << " completed" << std::endl;
void run() {
std::cout << id << ":" << countDown << std::endl;
std::cout << "Liftoff!" << std::endl;
#endif // LIFTOFF_H ///:~

The identifier id distinguishes between multiple instances of the task. If you only make a single instance, you can use the default value for ident. The destructor will allow you to see that a task is properly destroyed.

In the following example, the task s run( ) is not driven by a separate thread; it is simply called directly in main( ):

//: C11:NoThread.cpp
#include "LiftOff.h"
int main() {
LiftOff launch(10);;
} ///:~

When a class is derived from Runnable, it must have a run( ) function, but that s nothing special it doesn t produce any innate threading abilities.

To achieve threading behavior, you must use the Thread class.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire