Coroutine Examples |
A |
![]() |
Code Example A-1 counts the number of '0' characters in a string using cooperating tasks.
Code Example A-2 does the same, but illustrates the use of queues. The program loops forever, requiring a keyboard interrupt to terminate. It also never deletes the objects it allocates with new, and is thus not realistic.
Code Example A-2 Zero-Counter Using Queues |
// Zero-counter program using queues
#include <task.h>
#include <iostream.h>
class getLine : public task {
public:
getLine(qhead*, qtail*);
};
class countZero : public task {
public:
countZero(qhead*, qtail*);
};
class lineHolder : public object {
public:
char *line;
lineHolder(char* s) : line(s) { }
};
class numZero : public object {
public:
int zero;
numZero(int count) : zero(count) { }
};
getLine::getLine(qhead* countQ, qtail* lineQ)
{
numZero *qdata;
while( 1 ) {
cout << "Enter a string, ^C to end session: ";
char tmpbuf[512];
cin >> tmpbuf;
lineQ->put(new lineHolder(tmpbuf));
qdata = (numZero*) countQ->get();
cout << "Count of zeroes = " << qdata->zero << "\n";
};
resultis(1); // never gets here
}
countZero::countZero(qhead *lineQ, qtail *countQ)
{
char c;
lineHolder *inmessage;
while( 1 ) {
inmessage = (lineHolder*)lineQ->get();
char *s = inmessage->line;
int i = 0;
while( c = *s++ )
if( c == `0' )
i++;
numZero *num = new numZero(i);
countQ->put(num);
}
resultis(1); // never gets here
}
int main()
{
qhead *stringQhead = new qhead;
qtail *stringQtail = stringQhead->tail();
qhead *countQhead = new qhead;
qtail *countQtail = countQhead->tail();
countZero counter(stringQhead, countQtail);
getLine g(countQhead, stringQtail);
thistask->resultis(0);
return 0;
}