- #ifndef MYTHREAD_H
- #define MYTHREAD_H
- #include <QThread>
- class MyThread : public QThread
- {
- Q_OBJECT
- public:
- MyThread();
- void stop();
- volatile bool stopped;
- protected:
- void run();
- };
- #endif
- #include "myThread.h"
- #include <QtDebug>
- MyThread::MyThread()
- {
- stopped = false;
- }
- void MyThread::run()
- {
- int i=0;
- while(!stopped)
- {
- qDebug()<<"thread id:"<QThread::currentThreadId()<<":"<<i;
- i++;
- sleep(2);
- }
- stopped = false;
- }
- void MyThread::stop()
- {
- stopped = true;
- }
- #ifndef PRODUCER_H
- #define PRODUCER_H
- #include <QThread>
- class Producer : public QThread
- {
- Q_OBJECT
- public:
- Producer();
- protected:
- void run();
- };
- #endif
- #ifndef CONSUMER_H
- #define CONSUMER_H
- #include <QThread>
- class Consumer : public QThread
- {
- Q_OBJECT
- public:
- Consumer();
- protected:
- void run();
- };
- #endif
- #include "producer.h"
- #include "consumer.h"
- #include <QDebug>
- #include <QSemaphore>
- #define SIZE 50
- QSemaphore freeByte(SIZE);
- QSemaphore useByte(0);
- Producer::Producer()
- {
- }
- void Producer::run()
- {
- for(int i=0; i<SIZE; i++)
- {
- freeByte.acquire();
- qDebug()<<"produer:"<<i;
- useByte.release();
- sleep(1);
- }
- }
- Consumer::Consumer()
- {
- }
- void Consumer::run()
- {
- for(int i=0; i<SIZE; i++)
- {
- useByte.acquire();
- qDebug()<<"consumer:"<<i;
- freeByte.release();
- sleep(2);
- }
- }
- #ifndef THREAD_H
- #define THREAD_H
- #include<QThread>
- class Producer : public QThread
- {
- Q_OBJECT
- public:
- Producer();
- protected:
- void run();
- };
- class Consumer : public QThread
- {
- Q_OBJECT
- public:
- Consumer();
- protected:
- void run();
- };
- #endif
- #include "thread.h"
- #include <QDebug>
- #include <QMutex>
- #include <QWaitCondition>
- QMutex mutex;
- QWaitCondition empty, full;
- int num=0;
- int buffer[50];
- int useByte=0;
- Producer::Producer()
- {
- }
- void Producer::run()
- {
- for(int i=0; i<50; i++)
- {
- mutex.lock();
- if(useByte==50)
- empty.wait(&mutex);
- num++;
- buffer[i] = num;
- qDebug()<<"producer:"<<num;
- useByte++;
- full.wakeAll();
- mutex.unlock();
- sleep(1);
- }
- }
- Consumer::Consumer()
- {
- }
- void Consumer::run()
- {
- for(int i=0; i<50; i++)
- {
- mutex.lock();
- if(useByte==0)
- full.wait(&mutex);
- qDebug()<<"consumer"<<buffer[i];
- useByte--;
- empty.wakeAll();
- mutex.unlock();
- sleep(2);
- }
- }