Skip to content.

Sections
Personal tools
You are here: Home » ダウンロード » ThreadJack用 » queue

Document Actions
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <threadjack.h>
#include <tjmtsupp.h>
 

class Sender : public TJThread {
public:
    Sender(int number, TJQueue* q) : myNumber(number), myQueue(q) { }
    virtual void run () {
        char buf[256];
        for (int i=0; i<10; i++) {
            int wait = ::rand()%900+100;
            TJThread::sleep(wait);

            ::sprintf(buf, "Sender%d: No.%d, wt=%d", myNumber, i, wait);
            cout << buf << endl;
            myQueue->send(buf, strlen(buf));
        }
    }

private:
    int         myNumber;
    TJQueue* myQueue;
};

class Receiver : public TJThread {
public:
    Receiver(TJQueue* q) : myQueue(q) { }

    virtual void run () {
        char buf[256];
        while (1) {
            myQueue->receive(buf, sizeof(buf));
            cout << "##Receiver::run() : " << buf << endl;
            if (::strncmp(buf, "quit", 4) == 0) break;
            TJThread::sleep(1000);
        }
    }

private:
    TJQueue* myQueue;
};

int main() {
    TJQueue*   q = new TJQueue(32, 256);
    Receiver*  r = new Receiver(q);
    Sender*   s1 = new Sender(1, q);
    Sender*   s2 = new Sender(2, q);

    r->start();
    s1->start();
    s2->start();

    s1->join();
    s2->join();

    char buf[5];
    ::sprintf(buf, "quit");
    q->send(buf, sizeof(buf));
    r->join();

    delete q;

    return 0;
}