Previous Next Contents Index Doc Set Home


Coroutine Examples

A


This appendix shows the full text of the two sample programs discussed in Chapter 2, "The Coroutine Library".

Code Example A-1 counts the number of '0' characters in a string using cooperating tasks.

Code Example A-1     Zero-Counter Program 
// Simple zero-char counter program
#include <task.h>
#include <iostream.h>

class getLine : public task {
public:
    getLine();
};

getLine::getLine()
{
    char* tmpbuf = new char[512];
    cout << "Enter string: ";
    cin >> tmpbuf;
    resultis((int)tmpbuf);
}


class countZero : public task {
public:
    countZero(getLine*);
};

countZero::countZero(getLine *g)
{
    char *s, c;
    int i = 0;
    s = (char*)g->result();
    while( c = *s++)
        if( c == `0' )
            i++;
    resultis(i);
}

int main()
{
    getLine g;
    countZero c(&g);
    cout << "Count result = "
         << c.result() << "\n";
    thistask->resultis(0);
    return 0;
}

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;
}




Previous Next Contents Index Doc Set Home