// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

#include <QtCore/QThreadPool>
#include <QtCore/QRunnable>
#include <QtCore/QTime>

class Data
{
private:
    string s;
public:
    Data(string s);
    string GetS();
    void SetS(string s);
};

Data::Data(string s)
{
    this->s = s;
}

string Data::GetS()
{
    return s;
}

void Data::SetS(string s)
{
    this->s = s;
}

typedef Data *DataPtr;

class Processor : public QRunnable
{
private:
    Data *d;
protected:
    virtual void run();
public:
    Processor(Data *d);
};

Processor::Processor(Data *d)
{
    this->d = d;
}

void Processor::run()
{
    // simulate a lot of work that takes 0.1 second
    string s = d->GetS();
    QThread::msleep(100);
    d->SetS(s + "X");
}

typedef QThread *QThreadPtr;

void test(int njobs, int nthreads)
{
    // setup data
    DataPtr *d = new DataPtr[njobs];
    for(int i = 0; i < njobs; i++)
    {
        d[i] = new Data("X");
    }
    QTime tim;
    tim.start();
    QThreadPool pool;
    pool.setMaxThreadCount(nthreads);
    // submit jobs
    for(int i = 0; i < njobs; i++)
    {
        pool.start(new Processor(d[i]));
    }
    // wait for jobs to complete
    pool.waitForDone();
    int dt = tim.elapsed();
    cout << njobs << " jobs executing in " << nthreads << " threads : " << fixed << setprecision(1) << (dt / 1000.0) << " seconds" << endl;;
    // check data
    for(int i = 0; i < njobs; i++)
    {
        if(d[i]->GetS() != "XX") cout << "Ooops" << endl;
        delete d[i];
    }
    delete[] d;
}

void realmain()
{
    test(256, 1);
    test(256, 2);
    test(256, 4);
    test(256, 8);
    test(256, 16);
    test(256, 32);
    test(256, 64);
}
