时间:2021-07-01 10:21:17 帮助过:6人阅读
- #ifndef MYTHREAD_H
- #define MYTHREAD_H
- #include
- class MyThread : public QThread
- {
- Q_OBJECT
- public:
- MyThread();
- void stop();
- volatile bool stopped;
- protected:
- void run();
- };
- #endif
- #include "myThread.h"
- #include
- MyThread::MyThread()
- {
- stopped = false;
- }
- void MyThread::run()
- {
- int i=0;
- while(!stopped)
- {
- qDebug()<<"thread id:"
- i++;
- sleep(2);
- }
- stopped = false;
- }
- void MyThread::stop()
- {
- stopped = true;
- }
- #ifndef PRODUCER_H
- #define PRODUCER_H
- #include
- class Producer : public QThread
- {
- Q_OBJECT
- public:
- Producer();
- protected:
- void run();
- };
- #endif
- #ifndef CONSUMER_H
- #define CONSUMER_H
- #include
- class Consumer : public QThread
- {
- Q_OBJECT
- public:
- Consumer();
- protected:
- void run();
- };
- #endif
- #include "producer.h"
- #include "consumer.h"
- #include
- #include
- #define SIZE 50
- QSemaphore freeByte(SIZE);
- QSemaphore useByte(0);
- Producer::Producer()
- {
- }
- void Producer::run()
- {
- for(int i=0; i
- {
- freeByte.acquire();
- qDebug()<<"produer:"<
- useByte.release();
- sleep(1);
- }
- }
- Consumer::Consumer()
- {
- }
- void Consumer::run()
- {
- for(int i=0; i
- {
- useByte.acquire();
- qDebug()<<"consumer:"<
- freeByte.release();
- sleep(2);
- }
- }
- #ifndef THREAD_H
- #define THREAD_H
- #include
- 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
- #include
- #include
- 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:"<
- 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"<
- useByte--;
- empty.wakeAll();
- mutex.unlock();
- sleep(2);
- }
- }
http://www.bkjia.com/PHPjc/1103190.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1103190.htmlTechArticlelesson15-QT多线程 一、什么是线程 1、线程 进程:一个正在执行的程序,它是资源分配的最小单位 线程:程序执行的最小单位 进程出现了很...