使用QSemaphore来同步两个线程(QSDK examples)

#include <QtGui>


#include <stdio.h>
#include <stdlib.h>


//! [0]
#ifdef Q_WS_S60
const int DataSize = 300;
#else
const int DataSize = 100000;
#endif


const int BufferSize = 8192;
char buffer[BufferSize];


QSemaphore freeBytes(BufferSize);
QSemaphore usedBytes;

class Producer : public QThread
{
public:
    void run()
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        for (int i = 0; i < DataSize; ++i) {
            freeBytes.acquire();
           // buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
            buffer[i % BufferSize] = (char )i;
            //可以在这里加上sleep(1)来观察两者是否同步
            usedBytes.release();
        }
    }
};
class Consumer : public QThread
{
    Q_OBJECT
public:
    void run()
    {
        for (int i = 0; i < DataSize; ++i) {
            usedBytes.acquire();
    #ifdef Q_WS_S60
            QString text(buffer[i % BufferSize]);
            freeBytes.release();
            emit stringConsumed(text);
    #else
            fprintf(stderr, "%c", buffer[i % BufferSize]);
            freeBytes.release();
    #endif
        }
        fprintf(stderr, "\n");
    }


signals:
    void stringConsumed(const QString &text);


protected:
    bool finish;
};


int main(int argc, char *argv[])
{
#ifdef Q_WS_S60
    // Self made console for Symbian
    QApplication app(argc, argv);
    QPlainTextEdit console;
    console.setReadOnly(true);
    console.setTextInteractionFlags(Qt::NoTextInteraction);
    console.showMaximized();


    Producer producer;
    Consumer consumer;


    QObject::connect(&consumer, SIGNAL(stringConsumed(const QString&)), &console, SLOT(insertPlainText(QString)), Qt::BlockingQueuedConnection);


    producer.start();
    consumer.start();


    app.exec();
#else
    QCoreApplication app(argc, argv);
    Producer producer;
    Consumer consumer;
    producer.start();
    consumer.start();
    producer.wait();
    consumer.wait();
    return 0;
#endif
}


#include "semaphores.moc"  //注意这句话一定要加上。

你可能感兴趣的:(使用QSemaphore来同步两个线程(QSDK examples))