Created
September 14, 2015 12:25
-
-
Save theshadowx/4ce3b8d56e51dfb3df93 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QCoreApplication> | |
#include <iostream> | |
#include <QThread> | |
#include <QTime> | |
#include <unistd.h> | |
#include <QVector> | |
#include <QDebug> | |
#include <QMutex> | |
using namespace std; | |
#define BUFFER_SIZE 15 | |
QVector<QObject*> queue; | |
int queueItemcount = 0; | |
QMutex mutex; | |
class Producteur : public QThread | |
{ | |
public: | |
void run(); | |
}; | |
class Consomateur : public QThread | |
{ | |
public: | |
void run(); | |
}; | |
void Producteur::run() | |
{ | |
while(1){ | |
while(queueItemcount == BUFFER_SIZE){ | |
qDebug() << "Producteur attend"; | |
msleep(10); | |
} | |
if(mutex.tryLock(5)){ | |
QObject *newObject = new QObject; | |
qDebug() << "Producteur \t" << newObject <<" queueItemcount : " << (int)queueItemcount+1; | |
queue.push_front(newObject); | |
++queueItemcount; | |
mutex.unlock(); | |
} | |
msleep(10); | |
} | |
} | |
void Consomateur::run() | |
{ | |
while(1){ | |
while(queueItemcount == 0){ | |
qDebug() << "\033[1;31m Consomateur " << this << " attend\033[0m"; | |
msleep(10); | |
} | |
if(mutex.tryLock(5)){ | |
if(queueItemcount == 0){ | |
mutex.unlock(); | |
msleep(10); | |
continue; | |
} | |
QObject *ObjectFromQueue = queue.takeLast(); | |
qDebug() << "\033[1;31m Consomateur " << this << " \t:"<< ObjectFromQueue << " queueItemcount : " << (int)queueItemcount<<"\033[0m"; | |
delete ObjectFromQueue; | |
--queueItemcount; | |
mutex.unlock(); | |
} | |
msleep(10); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
QCoreApplication a(argc, argv); | |
Producteur *prodThread = new Producteur; | |
Consomateur *consThread1 = new Consomateur; | |
Consomateur *consThread2 = new Consomateur; | |
Consomateur *consThread3 = new Consomateur; | |
prodThread->start(); | |
consThread1->start(); | |
consThread2->start(); | |
consThread3->start(); | |
return a.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment