Skip to content

Instantly share code, notes, and snippets.

@theshadowx
Created September 14, 2015 12:25
Show Gist options
  • Save theshadowx/4ce3b8d56e51dfb3df93 to your computer and use it in GitHub Desktop.
Save theshadowx/4ce3b8d56e51dfb3df93 to your computer and use it in GitHub Desktop.
#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