Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
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 {
public:
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;
public:
LiftOff(int count, int ident = 0) :
countDown(count), id(ident) {}
~LiftOff() {
std::cout << id << "
completed" << std::endl;
}
void run() {
while(countDown--)
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);
launch.run();
} ///:~
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 |